Solved

Regex for state abbreviations

Posted on 2006-06-29
4
1,652 Views
Last Modified: 2008-01-09
I need a regular expression to validate two-letter US state codes, regardless of case.

I thought ^(?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])$ looked good, but it isn't working in my application (syntax error on client side).  I'm using Visual Web Developer Express.

Thanks in advance!
0
Comment
Question by:psk1
  • 2
  • 2
4 Comments
 
LVL 25

Expert Comment

by:clockwatcher
ID: 17016346
What error are you getting and how are you using it?  This works for me:

example.aspx
---------------
<%

dim re as New System.Text.RegularExpressions.Regex("^(?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])$")

Response.Write(re.IsMatch("ca") & "<BR>")
Response.Write(re.IsMatch("ci"))

%>
0
 
LVL 2

Author Comment

by:psk1
ID: 17020105
You know, I'm not sure what exactly is going on here.  I can't find where in the javascript generated by the aspx page this regex is really being applied.  Yet the error I get on the client side (but not in the developer) is "Syntax error in validation expression."

var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
    ValidatorOnLoad();
}

function ValidatorOnSubmit() {
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else {
        return true;
    }
}

var Page_Validators =  new Array(document.getElementById("vldPrimaryContactNameFirst_R"), document.getElementById("vldPrimaryContactNameLast_R"), document.getElementById("vldBusinessPhone_R"), document.getElementById("vldBusinessPhone"), document.getElementById("vldBusinessEmail_R"), document.getElementById("vldBusinessEmail"), document.getElementById("vldBusinessName_R"), document.getElementById("vldAddressLine1_R"), document.getElementById("vldCity_R"), document.getElementById("vldStateCode_R"), document.getElementById("vldStateCode"), document.getElementById("vldZip_R"), document.getElementById("vldZip"), document.getElementById("vldProjectedAnnualVolume"), document.getElementById("vldProjectedAnnualVolume_R"));

vldStateCode.validationexpression = "^(?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])$";

My other regular expression validators on the same page work fine.
0
 
LVL 25

Accepted Solution

by:
clockwatcher earned 250 total points
ID: 17022450
oh... ok... i see what you're doing now.  The (?i) construct isn't supported in javascript.  There's no option for a regular ASP.NET regex validator control to generate a case-insensitive client-side regular expression.  

One option is to disable the client script for that particular control--  vldStateCode.EnableClientScript = false;  And let the server do the validation and come back and tell you it isn't valid.

Another option would be to remove the (?i) and explain to your users in the validation message that it expects an uppercase abbreviation.

And a third option would be to hack the code that ASP.net creates a bit and replace its validator function with your own custom function for that particular control.  Here's an example.  It needs to be tested under different browser versions since ASP.net customizes the client-side script it spits out based on the browser it detects.  My javascript code shouldn't choke in any browser; just don't know if it will play well with the different browser specific javascript code that asp.net will spit out.  Unless MS went wacky somewhere, it should.  

customrehook.aspx
----------------------
<%@ Page language="c#"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <script language="javascript">
<!--
          function InstallCustomRegexHook(validator, newre)
          {
               // params:
               //      validator:  id of control you want to hook
               //      newre:  a regular expression object (not a string... the actual javascript regex object you want to use)

               var control = document.getElementById(validator);
               control.evaluationfunction = CustomRegexValidator;
               control.regex = newre;
          }

          function CustomRegexValidator(control)
          {
               var value = ValidatorGetValue(control.controltovalidate);
               // alert(value);
               return (control.regex.exec(value) != null);
          }

          function CustomRegexHookup()
          {

               // Call InstallCustomRegexHook for every regular expression control you want to explictly define with a custom javascript based regex

               if (Page_ValidationActive) {
                    InstallCustomRegexHook("RegularExpressionValidator1", /^(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])$/i );
               }
          }
// -->              
            </script>
      </HEAD>
      <body onload="CustomRegexHookup()">
            <form id="Form1" method="post" runat="server">
                  <P>
                        <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>&nbsp;
                        <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="invalid state" ControlToValidate="TextBox1"
                              ValidationExpression="^(?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])$"></asp:RegularExpressionValidator></P>
                  <P>
                        <asp:Button id="Button1" runat="server" Text="Button"></asp:Button></P>
            </form>
      </body>
</HTML>
----------------

To add it to your page, copy and paste the script block in the <head> element, replace the "RegularExpressionValidator1" with the id of the control you want to validate ("vldStateCode") in the CustomRegexHookup function and add the onload="CustomRegexHookup()" to your body tag.  Anyway, give it a try.

And what states are AS, AE, and AP?
0
 
LVL 2

Author Comment

by:psk1
ID: 17024029
American Samoa and APO/FPO addresses.

Thanks clockwatcher!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now