Solved

Regex for state abbreviations

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
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…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

813 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

11 Experts available now in Live!

Get 1:1 Help Now