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>
Your regex is incorrect, and your PHP usage is incorrect. In PHP regexs need delimiters.
A backslash in a PCRE regex escapes the next character. I would use:
[A-Z]\d[A-Z] \d[A-Z]\d
and in PHP (add anchors so the whole string has to match):
preg_match('/^[A-Z]\d[A-Z] \d[A-Z]\d$/', $string);
If the case is optional add either the i
modifier after the delimiter:
preg_match('/^[A-Z]\d[A-Z] \d[A-Z]\d$/i', $string);
or add the lowercase character range as well:
preg_match('/^[A-Za-z]\d[A-Za-z] \d[A-Za-z]\d$/', $string);
Regex Demo: https://regex101.com/r/cG9sG9/1
PHP Demo: https://eval.in/594444 (the 1 is true, for a match)
If the whitespace between the first grouping and second can vary use \h
and either the *
quantifier or the +
quantifier. The *
makes it not required (zero or more occurrences).