Solved

Regex for state abbreviations

Posted on 2006-06-29
4
1,830 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Suggested Solutions

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
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…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

751 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