3

I'm using ASP.NET MVC application and model has the following regular expression to validate US states.

This one works fine if user enter all upper case, but 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")]

thank you.

Yass
  • 592
  • 1
  • 8
  • 30
  • Is it for client side? If yes, you can't use `(?i)`. For server-side, you can use the `(?i)` modifier at the beginning of the pattern, I think. – Wiktor Stribiżew Dec 30 '15 at 19:38

3 Answers3

3

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Also, see more about case insensitive validation in ASP.NET [here](http://forums.asp.net/post/2248685.aspx) and [here](http://stackoverflow.com/a/15047806/3832970). – Wiktor Stribiżew Dec 30 '15 at 23:56
0

The list above is not as exhaustive - it is missing some military abbreviations. Trust me - you do not want to receive the ire of patriotic families trying to send stuff to their loved ones in the military.

Same technique - I added a few more.

^(([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]))$
williamohara
  • 57
  • 1
  • 8
0

I have used

[^,]*[A-Z]{2}

hopefully, it works for you.

Hamed
  • 5,867
  • 4
  • 32
  • 56