Regular Expression Example, Regular Expression in ASP.net

ASP.NET provides you some handfull validation controls like RequiredFiledValidator, RegularExpressionValidator etc. Most of the time we have to check whether user has given the correct number, date, time or anything as input. To validate such things we use RegularExpressionValidator.

The dash is a 'range separator'. Instead of listing the entire lowercase alphabet, we can merely list a-z, as above, to show all the characters. Therefore, in this example, basically, using [a-z] for the regular expression would mean that we would search the text, and only match, lower case alphabetic characters. That brings up another anomaly about Regular Expressions - case sensitivity. Yes, Regular Expressions ARE case sensitive. This means that if we wanted any alphabetic character to be matched, we would need to put in [a-z], plus [A-Z]. Of course, we could put numeric ranges here, too, like '[0-9]' to match ONLY numeric characters. Another special identifier '\d' does the same thing - the 'd' stands for a digit character.

The Caret (^)/(Shift-6), if it is INSIDE brackets will match anything BUT what is listed in the characters next to it - but - it 'negates' whatever is in the Regular Expression (like [^Aa] - this will match anything except the lower or upper case 'A'. However, if it is quite different when used outside brackets. Here, it will look for the characters next to it, and test them against only the BEGINNING of the string, but it looks for an exact match. For instance: '^Dav' will be found in the string 'David is here today', but it will not be matched in 'We're going to find David', since it's not at the beginning of the string.

The dollar sign ($), as opposed to the Caret, will look at the END of the target string. For instance, '$fox' will find a match in 'silver fox' but not in 'the fox jumped over the log'

The period (.) can be used like a wildcard. Anyone who has used databases should know a little about wildcards, hopefully. Let's say the Regular Expression was 'exp.' - It would match if it found 'expression', 'experience', or 'exponential'.

The question mark (?) matches the preceding character 0 or 1 times

The asterisk (*) matches the preceding character 0 or more times. It is also sort of like a wildcard.
The plus sign (+) matches the previous character 1 or more times.


using System;
using System.Collections.Generic;
using System.Text;

namespace ExampleUtil
{
public class RegExp
{

public static readonly string Url = "[a-zA-Z0-9-_\\$]+(//.[a-za-z0-9-_//$]+)?\\??" +
"[a-zA-Z0-9-_\\$]+=?[a-zA-Z0-9-_\\$]+(&[a-zA-Z0-9-_\\$]+=" +
"[a-zA-Z0-9-_\\$]+)*";">\\.[a-zA-Z0-9-_\\$]+)?\\??" +
"[a-zA-Z0-9-_\\$]+=?[a-zA-Z0-9-_\\$]+(&" +
"[a-zA-Z0-9-_\\$]+=[a-zA-Z0-9-_\\$]+)*";
public static readonly string Date = "(0[1-9]|[12][0-9]|3[01])[-]" +
"(0[1-9]|1[012])[-]((175[7-9])|(17[6-9][0-9])|(1[8-9][0-9][0-9])|" +
"([2-9][0-9][0-9][0-9]))";
// supports dates from 1-1-1757 to 31-12-9999 for SQL Server 2000 Date Range
public static readonly string Time = "(0[1-9]|[1][0-2])[:]" +
"(0[0-9]|[1-5][0-9])[:](0[0-9]|[1-5][0-9])[ ][A|a|P|p][M|m]";
public static readonly string Number = "[-+]?[0-9]*\\.?[0-9]*";
public static readonly string Digit = "[0-9]*";
public static readonly string NonNegative = "[+]?[0-9]*\\.?[0-9]*";

public static string MaxLength(int len)
{
return "[\\s\\S]{0," + len.ToString() + "}";
}
}
}

The ValidationErrorMessages class


using System.Collections.Generic;
using System.Text;

namespace Resource
{
public class ValidationErrorMessages
{

public static readonly string Url = "* Please enter a valid URL.<br>Valid " +
"characters are all alphanumeric characters and .?" +
"&_=-$<br> example: home.aspx?id=5&name=$my_name";
public static readonly string Required = "* Required";
public static readonly string Date = "* Please enter a valid date in dd-MM-yyyy format.";
public static readonly string Time = "* Please enter a valid time in hh:mm:ss am format.";
public static readonly string Number = "* Must be a valid number.";
public static readonly string Digit = "* Must be a valid whole number.";
public static readonly string NonNegative = "* Must be a non-negative number.";

public static string MaxLength(int len)
{
return "* Maximum " + len.ToString() + " characters are allowed.";
}
}
}



Defaul.aspx 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>RegExp Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>
Validation Example</h3>
<table border="1" width="50%">
<tr>
<td style="width: 200px">
<asp:Label ID="LabelComment"
runat="server" Text="Comment:">
</asp:Label></td>
<td>
<asp:TextBox ID="TextBoxComment" runat="server"
TextMode="MultiLine" Width="500px" />
<asp:RegularExpressionValidator ID="CommentValidator"
runat="server" ControlToValidate="TextBoxComment">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="LabelDate" runat="server"
Text="Date:"></asp:Label></td>
<td>
<asp:TextBox ID="TextBoxDate"
runat="server" Width="500px" />
<asp:RegularExpressionValidator ID="DateValidator" runat="server"
ControlToValidate="TextBoxDate"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="LabelTime" runat="server"
Text="Time:"></asp:Label></td>
<td>
<asp:TextBox ID="TextBoxTime" runat="server" Width="500px" />
<asp:RegularExpressionValidator ID="TimeValidator" runat="server"
ControlToValidate="TextBoxTime"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="LabelNumber" runat="server"
Text="Number:"></asp:Label></td>
<td>
<asp:TextBox ID="TextBoxNumber" runat="server" Width="500px" />
<asp:RegularExpressionValidator ID="NumberValidator" runat="server"
ControlToValidate="TextBoxNumber"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="LabelDigit" runat="server"
Text="Digit:"></asp:Label></td>
<td>
<asp:TextBox ID="TextBoxDigit" runat="server" Width="500px" />
<asp:RegularExpressionValidator ID="DigitValidator" runat="server"
ControlToValidate="TextBoxDigit"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="NonNegativeLabel" runat="server"
Text="Non Negative:"></asp:Label></td>
<td>
<asp:TextBox ID="TextBoxNonNegative" runat="server" Width="500px" />
<asp:RegularExpressionValidator ID="NonNegativeValidator" runat="server"
ControlToValidate="TextBoxNonNegative"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="UrlLabel" runat="server" Text="Url:">
</asp:Label></td>
<td>
<asp:TextBox ID="TextBoxUrl" runat="server" Width="500px" />
<asp:RegularExpressionValidator ID="UrlValidator" runat="server"
ControlToValidate="TextBoxUrl"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>


Defaul.aspx.cs page


using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using ExampleUtil;
using Resource;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CommentValidator.ValidationExpression = RegExp.MaxLength(50);
CommentValidator.ErrorMessage = ValidationErrorMessages.MaxLength(50);

DateValidator.ValidationExpression = RegExp.Date;
DateValidator.ErrorMessage = ValidationErrorMessages.Date;

TimeValidator.ValidationExpression = RegExp.Time;
TimeValidator.ErrorMessage = ValidationErrorMessages.Time;

NumberValidator.ValidationExpression = RegExp.Number;
NumberValidator.ErrorMessage = ValidationErrorMessages.Number;

DigitValidator.ValidationExpression = RegExp.Digit;
DigitValidator.ErrorMessage = ValidationErrorMessages.Digit;

NonNegativeValidator.ValidationExpression = RegExp.NonNegative;
NonNegativeValidator.ErrorMessage = ValidationErrorMessages.NonNegative;

UrlValidator.ValidationExpression = RegExp.Url;
UrlValidator.ErrorMessage = ValidationErrorMessages.Url;
}
}
Tags: , ,
Hot on Web:


About author