C#- Validation for US or Canadian zip code

前端 未结 3 738
旧时难觅i
旧时难觅i 2020-12-14 18:11

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.

相关标签:
3条回答
  • 2020-12-14 18:33

    The US zipcode validation which works "on my machine" is

    [RegularExpression(@"\d{5}$", ErrorMessage = "Invalid Zip Code")]
    
    0 讨论(0)
  • 2020-12-14 18:35

    If you are using Data Annotation Validators, you can use a RegularExpression attribute like this:

    [RegularExpression(@"(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstv‌​xy]{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)

    0 讨论(0)
  • 2020-12-14 18:37
        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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题