[Solved] UK Post Code RegEx

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
jane
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 4:49 pm

[Solved] UK Post Code RegEx

Post by jane »

Hello everyone,

I am trying to make a form which only allows those with postcodes 'AB' and 'CD' to proceed. The RegEx I am trying to tweak is:

((/^[A-ZA-z]{1,2}[0-9]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/).test(CustomerForm.PostCode.value))

Thanks for reading,
Jane
Last edited by jane on Fri Mar 02, 2007 6:56 am, edited 1 time in total.
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

Post by dude81 »

Try this

Code: Select all

((/^[AB|CD]$/si).test(CustomerForm.PostCode.value))
jane
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 4:49 pm

Post by jane »

No luck with that.

Thanks for your contribution,
Jane
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Maybe

Code: Select all

/^(?:AB|CD)[A-ZA-z]{1,2}[0-9]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/.test(Customer.PostCode.value)
Can you provide some examples of values it would be testing?
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

Post by dude81 »

I hope it should not take too big expression. It just requires AB or CD

Code: Select all

/(?AB|CD)/si
User avatar
veridicus
Forum Commoner
Posts: 86
Joined: Fri Feb 23, 2007 9:16 am

Post by veridicus »

I've worked with UK post codes and they can be extremely annoying. If you want to know a string begins with AB or CD that's simple. But if you're trying to validate the whole code that's more complicated. So far I like feyd's answer the best as it actually should validate the whole code if I remember how those post codes can look.
jane
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 4:49 pm

Post by jane »

feyd wrote:Maybe

Code: Select all

/^(?:AB|CD)[A-ZA-z]{1,2}[0-9]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/.test(Customer.PostCode.value)
Can you provide some examples of values it would be testing?
That doesn`t work feyd.

I would like to use strings like:

AB1 1LL
AB11 1LL
A1 1LL
AB11LL
AB111LL
AB1LL
User avatar
veridicus
Forum Commoner
Posts: 86
Joined: Fri Feb 23, 2007 9:16 am

Post by veridicus »

Try

Code: Select all

/^(?:AB|CD)[0-9]{1,2}[ ]?[0-9]?[A-Za-z]{2}$/
The only significant difference is that after the AB or CD there is never a letter.

This won't catch A1 1LL because you said you always want AB or CD.
jane
Forum Newbie
Posts: 7
Joined: Sun Feb 25, 2007 4:49 pm

Post by jane »

My mistake about A1.

Thanks a lot veridicus, that is exactly what the Doctor ordered.

Thanks once again,
Jane.
Post Reply