I am using following method to validate US or Canadian zip code, but i think it is not working fine for me. Please suggest me the changes in the regular expression.
The US zipcode validation which works "on my machine" is
[RegularExpression(@"\d{5}$", ErrorMessage = "Invalid Zip Code")]
If you are using Data Annotation Validators, you can use a RegularExpression attribute like this:
[RegularExpression(@"(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvxy]{1} *\d{1}[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvxy]{1}\d{1}$)", ErrorMessage = "That postal code is not a valid US or Canadian postal code.")]
(regex is from the link @huMptyduMpty posted above at http://geekswithblogs.net/MainaD/archive/2007/12/03/117321.aspx but my regex allows both upper and lower case letters)
var _usZipRegEx = @"^\d{5}(?:[-\s]\d{4})?$";
var _caZipRegEx = @"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$";
private bool IsUSOrCanadianZipCode(string zipCode)
{
var validZipCode = true;
if ((!Regex.Match(zipCode, _usZipRegEx).Success) && (!Regex.Match(zipCode, _caZipRegEx).Success))
{
validZipCode = false;
}
return validZipCode;
}
}