I have a PHP script that is processing some form data (by posting back to itself) and displaying the relevant form data in the form along with the resulting calculations. The relevant pieces of code that I'm having trouble with are shown below:
First bit of code:
if ($_POST["country"] == "select") {
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
}
else {
$country = ($_POST["country"]);
}
Second bit of code is as follows. Note that my intent is to trigger an error message if data entered into the zip field is not a 5-digit zip code:
if (empty($_POST["zip"])) {
if ($country == "United States") {
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
}
else {
if ($country == "United States") {
$zipCode = test_input($_POST["zip"]);
if (!preg_match("/^[0-9]{5}$/",$zipCode)){
$formResponse = "Some data was incorrectly entered or missing. Please try again.";
//$zip="";
}
}
}
}
Relevant code in form for zip code:
<input id="zip" type="text" name="zip" placeholder="Enter 5-digit zip code" value="<?php echo $zipCode;?>" />
With respect to the processing of form data, the zip code isn't working correctly:
- The if(empty(($POST["zip"]); piece of code works correctly and throws the correct error upon form submission.
- My RegEx doesn't seem to work as it doesn't throw an error if data of any kind is put into the zip field and suggests that all data has been properly submitted.
- On a "successful" processing, the $zipCode field is not being displayed.
Clearly, I've got something wrong with my logic / expression, but I've been looking at this for a while. If anyone has some suggestions, it would be appreciated.
Cheers! Mike