ASP.NET MVC 4 Zip Code Validation

18,093

Solution 1

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

Solution 2

[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; }
Share:
18,093
Admin
Author by

Admin

Updated on July 28, 2022

Comments

  • Admin
    Admin almost 2 years

    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

  • Jan
    Jan about 8 years
    Your answer should contain some explanation and not code only.
  • pianocomposer
    pianocomposer over 2 years
    Terrible idea. There are over 3,000 zip codes on the east coast that start with zero