1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

How would I validate a 5 digit zip code in PHP?



I have a PHP form. It asks for a 5 digit zip code, I have it set now to make sure they enter something in the field with Javascript validation, but how can I validate they have entered a 5 digit number? Please include sample code or link to sample code. Thanks so much.


5 Responses to “How would I validate a 5 digit zip code in PHP?”

  • solarisedesign says:

    You can either verify this value with Javascript or PHP, but I would probably recommend you use PHP, as Javascript validation won’t always work – e.g. if someone has javascript disabled.

    You can use PHP regular expressions to match many different things. In your case, the proper code to use would be

    <?php
    $user_zip = "12345"; //sample zip code
    $match = preg_match("#[0-9]{5}#", $user_zip);
    ?>

    The variable $match will either be 1 (for a match) or 0 (for no matches) – You can then use this to determine whether to accept the value or not.

    Report this comment

  • dane_62 says:

    I wrote the javascript once to validate a zip code box in a form but I don’t have the code in front of me. If no one else gets you a good answer, send me your e-mail address through my profile and i’ll send you the code ( it’s on my computer at home).

    Report this comment

  • Allison D says:

    It seems to me the simplest solution is to fix the width of the zip code form element to a max of 5, then use either JS or PHP to check that the data is >10000, which is a trivial comparison in either language.

    Report this comment

  • unlockedhed says:

    Hello,

    Below is an example PHP fragment for confirming that a ZIP code submitted by the user is indeed a 5-digit number. (This would not work for people from countries other than the U.S.)

    <?php
    if(preg_match("/^[0-9]{5}$/", $form_zipcode)) {
    echo "The ZIP code must be a 5-digit number.";
    }
    ?>

    Sean Colicchio
    Server Engineer
    Host My Site
    http://www.hostmysite.com/?utm_source=bb

    Report this comment

Leave a Reply

Spam Protection by WP-SpamFree

TigerDirect