Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Regex for state abbreviations

Posted on 2006-06-29
4
Medium Priority
?
2,112 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 1000 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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
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…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

926 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