Search code examples
javascripthtmlformsfunctionzipcode

Making sure that a user can't submit less than 5 numbers for zip code in a JavaScript form


I am building a registration form and I need a way of preventing users from submitting less than 5 numbers for the zip code. When I comment out my attempt for the else if entirely, the other function (making sure that users won't submit any letters) works. I am using return false at the end so that the form won't submit and I can test for bad input. Sorry for the lack of jsfiddle - it wouldn't let me submit forms for some reason (I am a noob, so that may be the reason). Here's a snippet of my code:

HTML:

<form name="reg" onSubmit="return formValidation();">    
<p>Zip Code: <input type="text" id="zip" maxlength="5" name="zip"></p>
<input type="submit" id="submitbutton" name="submitbutton" value="Submit" />
<div id="msg"></div> 
</form>

JS:

function formValidation()  
{  
    var zip = document.reg.zip; 
    allnumeric(zip);

function allnumeric(zip)
{   
    var numbers = /^[0-9]+$/;  
    if(zip.value.match(numbers))  
    {  
        document.getElementById("msg").innerHTML=("OK &#x2713;");
        msg.style.color="green";
    }  
    else if (zip.numbers < 5) /*DOES NOT COMPUTE*/
    {
        msg.innerHTML=("Has to be 5 numbers.");
        msg.style.color="red";
    }
    else
    {  
        msg.innerHTML=("Numbers only please.");
        msg.style.color="red";
    }  
};  
    return false;
};

Solution

  • You want zip.value.length, not zip.numbers.

    You can also do the whole thing with the regex:

    var numbers = /^\d{5}$/;  
    if(zip.value.match(numbers))  
    {  
        document.getElementById("msg").innerHTML=("OK &#x2713;");
        msg.style.color="green";
    }  
    else
    {  
        msg.innerHTML=("Numbers only please.");
        msg.style.color="red";
    }