Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 Zip Code Validation

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

[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

like image 419
user2406346 Avatar asked May 21 '13 16:05

user2406346


2 Answers

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; }
like image 79
Mike Hewitt Avatar answered Oct 15 '22 02:10

Mike Hewitt


[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; }
like image 29
Rajesh Tripathy Avatar answered Oct 15 '22 01:10

Rajesh Tripathy