Dorian06
Dorian06

Reputation: 49

php regex issues

I have a pattern match here that looks like it should work fine. However any input I give makes the conditional fail. I will handle the '99999-9999' case after I get the '99999' case working.

$ZipCode is a textfield that is being submitted on POST.

$ZipCode                        = $_POST["ZipCode"];

if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{$error_str .= "The zip code you enter must be in the form of: '99999' or '99999-9999'\n";}

if(isset($_POST['submit']))
{?><script>var error = <?= json_encode($error_str);?>;
   alert(error);
  </script>
<?}

'11111' fails and '111111' also fails

Upvotes: 2

Views: 73

Answers (1)

Mark Byers
Mark Byers

Reputation: 838076

Your code should work correctly. Example:

$ZipCode = "111111";

if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{
    echo "Incorrect format";
}

Result:

Incorrect format

Try entering some invalid input to see if the error message is displayed.


To handle both cases at once you can use this regular expression:

/^[0-9]{5}(?:-[0-9]{4})?$/

Upvotes: 2

Related Questions