Friday, January 19, 2007

Regular Expression : Validate State Abbreviation

Problem:
Validate user input.
State Abbreviations.
Only allow valid input

Solution:

using System.Text.RegularExpressions;

//input from user
string state = this.textBox1.Text.ToString().Trim().ToUpper();

if (Regex.IsMatch(state, "^(?:(A[KLRZ]*|C[AOT]*|D[CE]*|F[L]*|G[A]*|H[I]*|I[ADLN]*|K[SY]*|L[A]*|M[ADEINOST]*|N[CDEHJMVY]*|O[HKR]*|P[AR]*|R[I]*|S[CD]*|T[NX]*|U[T]*|V[AIT]*|W[AIVY]*))$") == true)
{
MessageBox.Show("Valid");
}
else
{
MessageBox.Show("InValid");
}


Results:
Good: A, AK, AZ
Bad: AS, AM

No comments: