1

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>
j08691
  • 204,283
  • 31
  • 260
  • 272
Mat UK
  • 11
  • 1
  • 2
  • 1
    possible duplicate of [UK Postcode Regex (Comprehensive)](http://stackoverflow.com/questions/164979/uk-postcode-regex-comprehensive) – Alex K. Feb 18 '12 at 18:47
  • 3
    Post code format is not same in all country. So there is not uniform regex that will work for all Post codes. – Shiplu Mokaddim Feb 18 '12 at 18:49

2 Answers2

0

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>
Beez
  • 2,081
  • 1
  • 20
  • 23
0

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.

rayfranco
  • 3,630
  • 3
  • 26
  • 38