Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Problem in zip code validation

    Hello! There is something wrong in the code below. What is it? Can you help me please? The form validation was working just fine when I added the last 'if' for zip code validation. The function didn't work and returned true. The code is:

    Code:
    <script type="text/javascript">
    function validateForm()
    {
    var y=document.forms["form"]["firstname"].value;
    var f=document.forms["form"]["zipcode"].value;
    var x=document.forms["form"]["email"].value;
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (y==null || y=="NAME")
      {
      alert("First name must be filled out");
      return false;
      }
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
      {
      alert("Not a valid e-mail address");
      return false;
      }
    }
    var re='/(^\d{5}$)/';
    if (f!=re)
      { 
      alert ("Not a valid address");
      return false;
      }
    }
    </script>
    Any ideas or advice? Thank you in advance!

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,022
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    Code:
    if (!/\d{5}/.test(f)) {
    alert ("Invalid zip code");
    // erase the field with wrong info in it
    // and refocus on it
    return false;
    }

    You may wish to use
    if (/^\d{5}\-?\d{4}$/gi.test(f)) { // 5 digits, optional hyphen, 4 digits
    as I understand some US zip codes are in the form 12345-6789


    Quizmaster: In 1918 the Czechs and the Slovaks united to form which country?
    Contestant: Prussia

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    nicknick (04-06-2012)

  • #3
    New to the CF scene
    Join Date
    Apr 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you very much Philip! Now it is working! Thank you again!
    Last edited by nicknick; 04-06-2012 at 02:12 PM.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •