Hi,
I need to validate Canada postal code (for example:M4B 1C7) using C# regular expressions.
Please help.
Thanks.
Hi,
I need to validate Canada postal code (for example:M4B 1C7) using C# regular expressions.
Please help.
Thanks.
I suggest the following:
bool FoundMatch = false;
try {
FoundMatch = Regex.IsMatch(SubjectString, "\\A[ABCEGHJKLMNPRSTVXY]\\d[A-Z] ?\\d[A-Z]\\d\\z");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
[ABCEFGHJKLMNPRSTVXY][0-9][ABCEFGHJKLMNPRSTVWXYZ][0-9][ABCEFGHJKLMNPRSTVWXYZ][0-9]
Canadian postal codes can't have certain letters. ( D, I, O, etc.) :D
EDIT: oh, and if you wanted a space in the middle you can use
[ABCEFGHJKLMNPRSTVXY][0-9][ABCEFGHJKLMNPRSTVWXYZ] [\s] [0-9][ABCEFGHJKLMNPRSTVWXYZ][0-9]
\s will match any whitespace, newline and tab included. If you don't want those you could either use ^ to remove newlines and tabs or look up the ascii for the space character.
Validating the format of a postal code without validating its meaning isn't worth it, since typos can still result in a valid postal code for the wrong address. You want to validate the code against the address database. See http://www.canadapost.ca/cpo/mc/business/productsservices/atoz/postalcodeproducts.jsf