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” />
</td>
<tr>
</tr>
</tr>
<tr>
<td>
Email Address:
</td>
<td>
<asp:TextBox runat=”server” ID=”txtEmail” />
</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” />
</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” />
</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” />
</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” />
</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.
Hi! nice site!
Thank you very much!