...

View Full Version : Validate postcode entry on form



dominicall
10-18-2002, 11:03 AM
Hi - hope someone can help.

I'm trying to validate a UK postcode format with the following script:

UK postcodes can be any of the following (A = alpha, N = numeric):

AN NAA, AAN NAA, ANN NAA, AANN NAA

For some reason, the following script returns true even if I enter something completely invalid such as 'dddddd'.

// check that UK post code is valid
function isValidPostcode(postcode) {
if (!(postcode.length == 6 || postcode.length == 7 || postcode.length == 8)) return false; //check not too short or long
if (!(isNaN(postcode.charAt(0)))) return false; //1st character must be a letter
if (isNaN(postcode.charAt(size-3))) return false; //first character of inward code must be numeric rule
if (!(isNaN(postcode.charAt(size-2)))) return false; //second character of inward code must be alpha rule
if (!(isNaN(postcode.charAt(size-1)))) return false; //third character of inward code must be alpha rule
if (!(postcode.charAt(size-4) == " ")) return false; //space in position length-3 rule
count1 = postcode.indexOf(" ");count2 = postcode.lastIndexOf(" "); //find first and last space - should be only 1
if (count1 != count2) return false; //only one space rule
return true;
}

Any one have any ideas????

Thanks

Dominic:confused:

beetle
10-18-2002, 02:58 PM
Uhm. Not too sure...I'm not good a reading through stuff like that. This should work for you...
function isValidPostcode(postcode) {
if (!/^[A-Z]{1,2}\d{1,2} \d[A-Z]{2}$/.test(postcode)) {
return false;
}
return true;
}If you need more validation, I'd be please if you checked out fValidate (http://www.peterbailey.net/fValidate). I can show you how do do the above validation with it as well.

Cheers, and happy coding :D

dominicall
10-18-2002, 04:10 PM
Thanks - will give it a try when I get back in tonight... and let you know how I get on.

I really must learn more about using regular expressions... LOL

Dominic :)

beetle
10-18-2002, 04:21 PM
I learned almost everything I know about regular expressions in JavaScript from this link

http://www.webreference.com/js/column5/

In fact, I still use it as a reference from time to time.

dominicall
10-18-2002, 04:40 PM
Hey beetle

It works - :D :D :D

Thanks a lot.... and for the reference for learning regular expressions - am definitely going to have a read.

You're a star.

Dominic



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum