简体   繁体   中英

How do I validate a Postcode on this form using JavaScript?

I'm not that experienced with JavaScript and I've been trying for a while now to make this form display an alert message if a postcode is entered in the wrong format when the user clicks the submit button. What I've achieved so far I've placed all inside one function which validates all of the fields, I'm using names to make reference to the fields from inside the function. (Sorry if I haven't indented properly)

var g=document.forms["myform"]["postcode"].value;
if (g==null || g=="")
{
    alert("Please enter your Post CODE");
    return false;
}
var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9]
[a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;
if(regPostcode.test(postcode) == false)
{
    alert("That Post Code is incorrect");
    return false;
}

Here's the HTML for the particular field inside the form im using

<div class=”field_container”><label>Post Code</label><input type=”text” name="postcode" id="postcode" /></div>

Also, you should add a simple accessibility enhancement like so:

<div class="field_container">
    <label for="postcode">Post Code</label> <!-- the "for" attribute should match the "id" attribute of the input it corresponds to -->
    <input type="text" name="postcode" id="postcode" />
</div>

Supposing that your regex is correct for the country you are aiming, I'd try something like this :

var g = document.forms["myform"]["postcode"].value;
var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9]
    [a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;
if (!g)
{
    alert("Please enter your Post CODE");
    return false;
}
if (!g.match(regPostcode))
{
    alert("That Post Code is incorrect");
    return false;
}

As @Shiplu said, there is not uniform regex that will work for Post codes for every countries. You should make sure you want to block form submission from people living in some other countries.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM