Jessica Mather Jessica Mather - 5 months ago 8
PHP Question

Why is my PHP not validating?

I am trying to make it so that if a person inputs the wrong postal code format or leaves the input null it will give an error. I am trying to figure out why it isn't working. Please help!

<td>Postal Code</td>
<td>
<input type="text" id="postal_code" name="postal_code" value="<?php if($_POST['postal_code'] == null){ echo '';}else{echo $_POST['postal_code'];}?>"/>
</td>
<td class="error" colspan="2">
<?php
if(isset($_POST['send_bulkform']) && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']) || isset($_POST['send_studentform']) && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']))
{
echo "Required, ex. A1A 1A1.";
}
elseif(isset($_POST['send_bulkform']) && $_POST['postalcode'] == null || isset($_POST['send_studentform']) && $_POST['postalcode'] == null)
{
echo "Required, ex. A1A 1A1.";
}
?>
</td>
</tr>

Answer

The problem is with this line:

if(isset($_POST['send_bulkform'])  && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']) || isset($_POST['send_studentform']) && $_POST['postalcode'] != preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code']))

1 - preg_match returns 1 for match or 0 for no match. So your test:

$_POST['postalcode'] != preg_match(...)

makes no sense and will most of the time be "true". Just use:

 if(preg_match(...))

2 - Regexp inside preg_match is malformed. Replace:

preg_match("[A\-Za\-z][0\-9][A\-Za\-z] [0\-9][A\-Za\-z][0\-9]",$_POST['postal_code'])

with:

preg_match("/[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]/",$_POST['postal_code'])