Custom DataAnnotation for US States

Pivoting off this post by Phil Haack about creating custom data annotations, I found myself in need of one today when putting together some code for a project for the spousal unit. I wanted to be sure that a given field contained a valid abbreviation for a U.S. State.

It’s simple, but it works. I’m going to be creating a lot of these custom validators now that I know how easy it is. Let’s go to the code:

public class IsStateAttribute : ValidationAttribute
{
private static string stateAbbreviationsRegex =  @”\A(?:AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FL|FM|GA|GU|HI|ID|IL|IN|

IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|

NC|ND|MP|OH|OK|OR|PW|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|

WY|AE|AA|AP)\Z”;
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
var state = (string)value;
if (Regex.IsMatch(state, stateAbbreviationsRegex))
{
return true;
}

return false;
}
}

A couple of things to notice:

1. If there is no entry, the attribute returns true. This is another tidbit I got from Phil, let the RequiredAttribute do its thing. We’re only here to validate if the value is present.

2. For the keen-eyed, there are more than 50 entries in the regex. Why? Because I included U.S. Territories like Guam (Guam is a funny word in and of itself. Back in the stand-up comedy days, I used it more than once in a punchline. Sorry if I’m offending anyone reading this in Guam.) as well as military abbreviations. You don’t have to use them in whatever drop-down you’re filling this field with, I added them for completeness.

Usage is what you would expect:

[IsState(ErrorMessage="Please Enter a Valid State Abbreviation")]
[Required(ErrorMessage = "State is Required")]
public string State { get; set; }

Enjoy!

Leave a Reply