Monday, March 26, 2007 12:58 PM Trivium DawnWalker

Implementing Regular Expressions

Using regular expressions in ASP.Net is even easier than implementing them in plain html and yet few developers are using them. In this article I will show two ways of implementing Regular Expressions, using a Regular Expression Validator and using plain Javascript in ASP.Net. Both examples are very very simple. We will validate a telephone number and an email address.

How to Implement Regular Expressions in ASP.Net with Validator Controls.

1) Create a new a page in a web application project in visual studio.
2) Lets create a basic table with space for a Telephone Number, Email Address and submit button. Use the following code if you wish:
 <table>
  <tr>
   <td>
    Telephone Number:
   </td>
   <td>
    <asp:TextBox runat="server" ID="txtTelNumber" />&nbsp;
   </td>
   <tr>
   
   </tr>
  </tr>
  <tr>
   <td>
    Email Address:
   </td>
   <td>
    <asp:TextBox runat="server" ID="txtEmail" />&nbsp;
   </td>
   <tr>
   
   </tr>
  </tr>
  <tr>
   <td colspan="2" style="text-align:right">
    <asp:Button runat="Server" ID="btnSubmit" Text="Submit" />
   </td>
  </tr>
 </table>
 
3) Then, in the empty cells add RegularExpressionValidator Controls from your toolbox.
4) Give each of your validators a descriptive ID and specify the control that validator should check.

Now, for our telephone number validator we are going use the same expression that I used in my preveious post. Under the controls Properties, set the ValidationExpression = ^(\()?(011|012)(\)|-)?([0-9]{3})?([0-9]{4}|[0-9]{4})$

For the email validator, click on the (...)button in the ValidationExpression Box. A popup box will be presented, in this box you can enter your own custom validation OR select a predefined regEx. In this case select the Internet Email Address.

Do yourself a favour and enter your own custom error messages for both validators.

Now run the page and test it. The moment the user clicks the submit button it validates both fields and if the fields comply with their respective regular expressions then the postback will proceed HOWEVER, should either NOT comply with their regular expression the postback will not occur and the error message will be shown. Once a compliant Telephone Number and/or email address is entered, the error message will disappear and the user can submit the form again.

Here is the whole ASP.Net Code for the above example:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <table>
                <tr>
                    <td>
                        Telephone Number:
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="txtTelNumber" />&nbsp;
                    </td>
                    <td>
                        <asp:RegularExpressionValidator
                            ID="regExTelephone" runat="server" ControlToValidate="txtTelNumber" Display="Dynamic"
                            ErrorMessage="Please enter a valid Telephone Number" ValidationExpression="^(\()?(011|012)(\)|-)?([0-9]{3})?([0-9]{4}|[0-9]{4})$"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        Email Address:
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="txtEmail" />&nbsp;
                    </td>
                    <td>
                        <asp:RegularExpressionValidator
                            ID="regExEmail" runat="server" ControlToValidate="txtEmail" Display="Dynamic"
                            ErrorMessage="Please enter a valid Email Address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align:right">
                        <asp:Button runat="Server" ID="btnSubmit" Text="Submit" />
                    </td>
                </tr>
            </table>
    </div>
    </form>
</body>
</html>

 


How to Implement Regular Expressions in ASP.Net using BLOCKED SCRIPT

1) Create a new a page in a web application project in visual studio.
2) Lets create a basic table with space for an Email Address and submit button. Use the following code if you wish:
 <table>
  <tr>
   <td>
    Email Address:
   </td>
   <td>
    <asp:TextBox runat="server" ID="txtEmail" />&nbsp;
   </td>
  </tr>
  <tr>
   <td colspan="2" style="text-align:right">
    <asp:Button runat="Server" ID="btnSubmit" Text="Submit" />
   </td>
  </tr>
 </table>
 
3) In the your header tags create a script block and write the neccessary functions to check the email entry. You can use the following script:

<script type="text/javascript">
    function ValidateEmail()
    {
      //Declare regular expression
      var re = new RegExp('^.+@[^\.].*\.[a-z]{2,}$');

      if (window.document.getElementById('txtEmail').value.match(re))
      {
        //allow postback to continue
        return true;
      }
      else
      {
        //inform user that the Telephone Number is not valid
        alert("Email not valid");
       
        //Set the focus on non-compliant field
        window.document.getElementById('txtEmail').focus();
       
        //Prevent the postback
        return false;
      }
    }
</script>

4) Then simply add the following attribute to your submit button:
 OnClientClick="BLOCKED SCRIPTreturn ValidateEmail();"
 

Here is the full code for this page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function ValidateEmail()
    {
      //Declare regular expression
      var re = new RegExp('^.+@[^\.].*\.[a-z]{2,}$');

      if (window.document.getElementById('txtEmail').value.match(re))
      {
        //allow postback to continue
        return true;
      }
      else
      {
        //inform user that the Telephone Number is not valid
        alert("Email not valid");
       
        //Set the focus on non-compliant field
        window.document.getElementById('txtEmail').focus();
       
        //Prevent the postback
        return false;
      }
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <table>
                <tr>
                    <td>
                        Email Address:
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="txtEmail" />&nbsp;
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align:right">
                        <asp:Button runat="Server" ID="btnSubmit" OnClientClick="BLOCKED SCRIPTreturn ValidateEmail();" Text="Submit" />
                    </td>
                </tr>
            </table>
    </div>
    </form>
</body>
</html>

 


And there we go. Now nobody who has read can say they don't know how to implement Regular expressions. I realised that this isn't the most complete guide to regular expressions but Rome wasn't built in a day. This is aimed at those people who have never in their lives implemented a Regular Expression.

I would appreciate any feedback and/or suggestions you may have on this or even requests pertaining to Regular Expressions.


 

kick it on DotNetKicks.com Filed under: , , ,

Comments

# Implementing Regular Expressions

Monday, March 26, 2007 5:20 PM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# re: Implementing Regular Expressions

Tuesday, March 27, 2007 8:57 AM by Vie

Hey there..  

I'm quite familiar with and passionate about regular expressions and their use within ASP.NET and believe you've created a very nice "beginners guide to" article.

- An oversight, but you need to set the ControlToValidate field on the regular expression validators to the particular control you wish to validate against.

- In point 4 of the manual Javascript method, you'll notice that the Community Server editor tried to prevent what it believed to be a script injection attack of some sort.  Its not mandatory for the OnClientClick property to include "java script:" (without the space), so you can leave this out anyway.

- Regular Expression validation will pass if the control is empty.

It makes sense though, in the case of wanting to allow nullable controls, and only enforce validation if they actually enter something.  So, to set controls to be required as well, you will need to use a RequiredFieldValidator on the same control as well.  (if placing the two validators next to each other, you may want to set the Display property to dynamic, else it may look weird).

- The JScript regular expression engine is good, but not as good as the .NET server side validation.

Once you become a seasoned Regular Expression wizard, you'll start wanting to use some of the more advanced RegEx features, which unfortunately are lacking in JScript.  Specific things like back and forward referencing will not validate in script.  But, and this is the beauty of the RegularExpressionValidator, is that on postback it will validate again on the server side and should then work.

- ValidationSummary controls are really neat!

While inline error messages are great, being able to show a summary at the top or bottom of your page detailing the errors in bullet form can be really useful too.

Great work! I look forward to the next part! :)

# re: Implementing Regular Expressions

Tuesday, July 10, 2007 8:07 AM by RAJASEKHAR

I WANT

HOW TO WRITE REGULAR EXPRESSIONS

TO CHECK PHONE NUMBER HOW CAN YOU WRITE

"^(\()?(011|012)(\)|-)?([0-9]{3})?([0-9]{4}|[0-9]{4})$

HOW CAN YOU WRITE THIS

PLEASE EXPLAIN HOW TO WRITE THAT

# re: Implementing Regular Expressions

Tuesday, July 17, 2007 11:04 PM by Trivium DawnWalker

I'll be honest with you RAJASEKHAR, I have no idea what you mean.

Do you want to know how to write your own regular expressions? If so, writing them yourself can be very difficult. Why don't you look at www.regular-expressions.info for more information.

Good luck!

# re: Implementing Regular Expressions

Friday, September 28, 2007 9:00 AM by suganya

when i enter somw text in textbox it will not allow only <> using regular expression.

# Zolpidem.

Friday, July 11, 2008 7:23 PM by Zolpidem.

Cheap zolpidem. Zolpidem tartrate. Cheap zolpidem persriptions. Zolpidem eszopiclone indications. Zolpidem overdose. Zolpidem.

# Lipitor and alcohol.

Friday, July 18, 2008 11:38 AM by Lipitor.

Lipitor online. Lipitor side effects. Lipitor. Lipitor dangers.

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: