Created
December 5, 2013 19:44
-
-
Save jeremykdev/7812536 to your computer and use it in GitHub Desktop.
Custom data annotation validation attribute to validate that data is a two character U.S. state abbreviation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel.DataAnnotations; | |
using System.Linq; | |
sealed public class UsStateTwoCharacterAbbreviationAttribute : ValidationAttribute | |
{ | |
private readonly string[] validStateAbbr = new string[] { "AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY" }; | |
public UsStateTwoCharacterAbbreviationAttribute() | |
: base("must be a two character U.S. state abbreviation") | |
{ | |
} | |
public override string FormatErrorMessage(string name) | |
{ | |
return String.Format("{0} {1}", name, ErrorMessageString); | |
} | |
public override bool IsValid(object value) | |
{ | |
bool isValid = false; | |
if(!String.IsNullOrWhiteSpace(value.ToString())) | |
{ | |
if(value.ToString().Length == 2 && this.validStateAbbr.Contains(value.ToString())) | |
{ | |
isValid = true; | |
} | |
} | |
return isValid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment