Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

US State Regular expression with case sensitive

I'm working on an ASP.NET MVC application, and my model has a regular expression to validate US states.

This regular expression works fine if the user enters all upper case, but it is not working for lower case/camel case scenarios.

[RegularExpression(@"^((A[ELKSZR])|(C[AOT])|(D[EC])|(F[ML])|(G[AU])|(HI)|(I[DLNA])|(K[SY])|(LA)|(M[EHDAINSOT])|(N[EVHJMYCD])|(MP)|(O[HKR])|(P[WAR])|(RI)|(S[CD])|(T[NX])|(UT)|(V[TIA])|(W[AVIY]))$", ErrorMessage = "Invalid State")]
public string State { get; set; }

I tried this one, but no luck.

[RegularExpression(@"^(?-i:A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$", ErrorMessage = "Invalid State")]

How can I fix my regular expression to match a US state, regardless of case?

like image 542
Yass Avatar asked Oct 15 '25 17:10

Yass


1 Answers

Since this expression can be used for client side validation (and thus requires ECMA regex syntax, that is, JavaScript-compatible regular expression) you cannot use an inline modifier like (?i) let alone the toggled version (?i:...).

You have to double each letter with the lowercase counterpart:

^(([Aa][EeLlKkSsZzRr])|([Cc][AaOoTt])|([Dd][EeCc])|([Ff][MmLl])|([Gg][AaUu])|([Hh][Ii])|([Ii][DdLlNnAa])|([Kk][SsYy])|([Ll][Aa])|([Mm][EeHhDdAaIiNnSsOoTt])|([Nn][EeVvHhJjMmYyCcDd])|([Mm][Pp])|([Oo][HhKkRr])|([Pp][WwAaRr])|([Rr][Ii])|([Ss][CcDd])|([Tt][NnXx])|([Uu][Tt])|([Vv][TtIiAa])|([Ww][AaVvIiYy]))$

See demo

like image 148
Wiktor Stribiżew Avatar answered Oct 17 '25 07:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!