Solved

Regex for state abbreviations

Posted on 2006-06-29
4
1,639 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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

758 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

22 Experts available now in Live!

Get 1:1 Help Now