Chris Kettenbach wrote:
Does anyone know of a regualr expression to validate US and Canadian Postal
Codes?
I want to be able to accept ##### or #####-#### or Canadian A#A #A# that is
alpha,number,alpha number,alpha,number.
I am new to regular expressions. The US 5 digit part is easy, but I get
stuck after that.
var pattern = new RegExp(/\\d{5}/)
Any ideas? Thanks everybody.
Chris
Firstly there are two ways of creating a RegExp, and your example mixes
the two up.
The first is:-
r=new RegExp("Pattern", "Optional Switches g and i");
The second is a Regular Expression Literal
r=/Pattern/Optional Switches;
Note that with the first the Pattern must be in a string, and needs to
use escapes for backslashes \\
In terms of your requirement, I am sure others will have better
suggestions but you could try the following:-
var r=/^(\d{5}|\d{5}-\d{4}|[A-Za-z]\d[A-Za-z] \d[A-Za-z]\d)$/;
Same as:-
var r=new RegExp("^(\\d{5}|\\d{5}-\\d{4}|[A-Za-z]\\d[A-Za-z]
\\d[A-Za-z]\\d)$");
Note that the ^ will prohibit any leading characters, and $ will
prohibit any trailing characters, the | is an alternative marker, and I
assume only one space between A#A #A#
Hope this helps.
Julian