How to validate Canada Postal Code in C#

Canadian postal code contains both letters and numbers in 6 or 7 characters, such as M3A 1J6, or M3A1J6. Furthermore, not all 26 letters are being used in the letter section of Canadian postal code. See the function below

public static bool IsPostalCode(string postalCode)
{
 
      //Canadian Postal Code in the format of "M3A 1A5"
      string pattern = "^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$";
 
       Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
 
       if (!(reg.IsMatch(postalCode)))
              return false;
       return true;
}
Advertisements