ASP.NET MVC 4邮政编码验证

时间:2021-03-02 16:36:48

I am using ASP.NET MVC 4 and I am looking for a attribute for Zip Code Validation

我正在使用ASP.NET MVC 4,我正在寻找邮政编码验证的属性

[Required(ErrorMessage = "Zip Code is Required")]
[ZipCode]
public string ZipCode { get; set; }

I know this doesn't work, but this is what I am looking for.

我知道这不起作用,但这正是我要找的。

Can anyone Help

谁能帮忙

I need the Zip for just USA

我需要美国的Zip

2 个解决方案

#1


18  

You need to use a Regex. Try something like this.

你需要使用正则表达式。尝试这样的事情。

[Required(ErrorMessage = "Zip is Required")]
[RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip")]
public string Zip { get; set; }

#2


1  

[Display(Name = "Zip Code")]
[StringLength(10, MinimumLength = 5)]
[RegularExpression("(^\\d{5}(-\\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\\d{1}[A-Z]{1} *\\d{1}[A-Z]{1}\\d{1}$)", ErrorMessage = "Zip code is invalid.")] // US or Canada
[Required(ErrorMessage = "Zip Code is Required.")]
public String ZipCode { set; get; }

#1


18  

You need to use a Regex. Try something like this.

你需要使用正则表达式。尝试这样的事情。

[Required(ErrorMessage = "Zip is Required")]
[RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip")]
public string Zip { get; set; }

#2


1  

[Display(Name = "Zip Code")]
[StringLength(10, MinimumLength = 5)]
[RegularExpression("(^\\d{5}(-\\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\\d{1}[A-Z]{1} *\\d{1}[A-Z]{1}\\d{1}$)", ErrorMessage = "Zip code is invalid.")] // US or Canada
[Required(ErrorMessage = "Zip Code is Required.")]
public String ZipCode { set; get; }