After a quick search on Google for an Actionscript Postcode validator nothing came up, so I thought I’d write one and post it here:
var postcode
:String =
"N5 1BU";
var postcodeExpression
:RegExp =
/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})$/;
var isValid
:Boolean = postcodeExpression
.test(postcode
);
Hope someone finds it useful, I got the regular expression from Wikipedia and also a thanks to Tavis for teaching me about RegExp.
UPDATE October 6, 2009, 13:39:
It was recently bought to my attention that the reg ex above only works if the postcode contains a space in the correct place. However, some forms have only one field for postcode input, and if you want to validate without the space use this:
var postcode
:String =
"N51BU";
var postcodeExpression
: RegExp =
/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$/;
var isValid
:Boolean = postcodeExpression
.test(postcode
);
Or you can easily strip white spaces using this:
var postcode
:String =
"N5 1BU";
var postcodeExpression
: RegExp =
/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$/;
var isValid
:Boolean = postcodeExpression
.test(postcode
.split(" ").join(""));
UPDATE February 3, 2010, 16:46:
I haven’t had to use this for a while, but when using it today I was confused as to why it wasn’t working… turns out it’s case sensitive. A little annoying, so to make it none case sensitive you have to add an “i” (which stands for case insensitive) to the end as below. Thanks (again) to Tavis for telling me that one.
var postcode
:String =
"N5 1BU";
var postcodeExpression
: RegExp =
/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$/i;
var isValid
:Boolean = postcodeExpression
.test(postcode
.split(" ").join(""));
Thanks for the validation code.
13 Nov 2009We can also use s? for validating postcodes with or without space in between.
i.e use s? where space is expected.
/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])s?[0-9][ABD-HJLNP-UW-Z]{2})$/;