hzrcan
hzrcan

Reputation: 69

Zip code based on a array with errors

I want to develop a zip code finder, the zip code consists of 4 digits and two letters. If the zip code is correct, the user will receive a confirmation that we deliver in that district. If not, a message that we don't deliver there.

And if the zip code doesn't contain the correct criteria an error with: enter the correct zip code 4 digits and 2 letters.

Here's a rough mockup of the php:

<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
    $postcode = array(6458,7493,6002,7520); 
    if(in_array($_POST['postcode'],$postcode))
    {
            echo 'We deliver on that district';
    }
    else
    {
        echo  'This order can not be delivered in that area';
    }
}


function IsPostcode($value) {
return preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $value);
}

if(IsPostcode($_POST['postcode'])) {
    echo 'Correct Zip code';
}
else {
    echo 'Incorrect zip code enter 4 letters and 2 numbers';
}

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="postcode" />
<input type="submit" value="verstuur" />
</form>

Thanks in advance

Upvotes: 0

Views: 632

Answers (1)

chris85
chris85

Reputation: 23880

Give this a try

<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
    $postcode = array(6458,7493,6002,7520);
    if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
        if(in_array($_POST['postcode'],$postcode)) {
            echo 'We deliver on that district';
        } else {
            echo  'This order can not be delivered in that area';
        }
    } else {
        echo 'Incorrect zip code enter 4 letters and 2 numbers';
    }
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="text" name="postcode" />
    <input type="submit" value="verstuur" />
</form>

It should first check if it meets your regex and if it does then check if they are inside of a range you've allowed. Your regex doesn't match the allowed addresses currently so these all will be This order can not be delivered in that area or Incorrect zip code enter 4 letters and 2 numbers.

You also don't need a function that just returns a the result of a native PHP function.

Upvotes: 0

Related Questions