C#- 验证美国或加拿大邮政编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14942602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:30:27  来源:igfitidea点击:

C#- Validation for US or Canadian zip code

c#asp.net.net

提问by Sunil Singh

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.

我正在使用以下方法来验证美国或加拿大的邮政编码,但我认为它对我来说效果不佳。请建议我修改正则表达式。

private bool IsUSorCanadianZipCode(string zipCode)
    {
        bool isValidUsOrCanadianZip = false;
        string pattern = @"^\d{5}-\d{4}|\d{5}|[A-Z]\d[A-Z] \d[A-Z]\d$";
        Regex regex = new Regex(pattern);
        return isValidUsOrCanadianZip = regex.IsMatch(zipCode);
    }

Thanks.

谢谢。

采纳答案by d.moncada

    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;
    }
}

回答by John Washam

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

如果您正在使用数据注释验证器,您可以使用这样的 RegularExpression 属性:

[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.aspxbut my regex allows both upper and lower case letters)

(正则表达式来自上面发布的链接@huMptyduMpty http://geekswithblogs.net/MainaD/archive/2007/12/03/117321.aspx但我的正则表达式允许大写和小写字母)

回答by Bogdan Mates

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

“在我的机器上”工作的美国邮政编码验证是

[RegularExpression(@"\d{5}$", ErrorMessage = "Invalid Zip Code")]