Click here to Skip to main content
15,388,688 members
Articles / Web Development / ASP.NET
Posted 13 Aug 2008

Tagged as


47 bookmarked

Common Validation and Length Validation with Regular Expressions in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.59/5 (15 votes)
20 Aug 2008CPOL2 min read
Common validation and length validation with Regular Expressions in ASP.NET.


Input validation is very common and important in any kind of application. In the case of web applications, server side validation is a must, and client side validation is highly anticipated. As you know, ASP.NET provides you with a handful of validation controls like RequiredFiledValidator, RegularExpressionValidator etc. Most of the time, we have to check whether the user has given the correct number, date, time, or anything as input. To validate such things, we use the RegularExpressionValidator.

In this article, I'll provide a Util class full of Regular Expressions for the most common input validation requirements. The main part is the length validation of a TextArea control. As you know, in the case of a TextField, you can easily get its max length. But for TextArea, you cannot do that. So normally, we have to write a JavaScript function to check the length before form submit.

But in ASP.NET, when you use a TextBox and set the TextMode property as MultiLine, the MaxLength property does not work. So if you want to put a restriction to limit the input length of the TextBox, you have to find an alternate way.

Here, I'll show how you can do this by simply writing a Regular Expression.

The Code

The RegExp class:

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

namespace Util
    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-_\\$]+(&" + 
        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])|" + 
               // 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 ValidationMessages class:

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

namespace Resource
    public class ValidationMessages

    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.";

Using the Code

The usage is very simple. See the example page.

Defaul.aspx page
<%@ Page Language="C#" AutoEventWireup="true" 
     CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
                Validation Example</h3>
            <table border="1" width="50%">
                    <td style="width: 200px">
                        <asp:Label ID="CommentLabel" 
                            runat="server" Text="Comment:">
                        <asp:TextBox ID="CommentTextBox" runat="server" 
                             TextMode="MultiLine" Width="500px" />
                        <asp:RegularExpressionValidator ID="CommentValidator" 
                          runat="server" ControlToValidate="CommentTextBox">
                        <asp:Label ID="DateLabel" runat="server" 
                        <asp:TextBox ID="DateTextBox" 
                           runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="DateValidator" runat="server" 
                        <asp:Label ID="TimeLabel" runat="server" 
                        <asp:TextBox ID="TimeTextBox" 
                           runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="TimeValidator" runat="server" 
                        <asp:Label ID="NumberLabel" runat="server" 
                        <asp:TextBox ID="NumberTextBox" 
                           runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="NumberValidator" runat="server" 
                        <asp:Label ID="DigitLabel" runat="server" 
                        <asp:TextBox ID="DigitTextBox" 
                           runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="DigitValidator" runat="server" 
                        <asp:Label ID="NonNegativeLabel" runat="server" 
                           Text="Non Negative:"></asp:Label></td>
                        <asp:TextBox ID="NonNegativeTextBox" 
                               runat="server" Width="500px" />
                          ID="NonNegativeValidator" runat="server" 
                        <asp:Label ID="UrlLabel" runat="server" Text="Url:">
                        <asp:TextBox ID="UrlTextBox" 
                              runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="UrlValidator" runat="server" 
Defaul.aspx.cs page
using System;
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 Util;
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 = ValidationMessages.MaxLength(50);

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

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

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

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

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

        UrlValidator.ValidationExpression = RegExp.Url;
        UrlValidator.ErrorMessage = ValidationMessages.Url;


Here, the URL validator expression and message were needed for my business requirements. If you have a different requirement, then customize it.

My Other Articles


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sowkot Osman
Software Developer (Senior)
Australia Australia
-7 years of extensive experience in devloping both desktop and web applications in C#.NET, VB.NET and ASP.NET, ASP.NET MVC 3.0/4.0
-5 years of experience in developing web applications in J2EE, Free Marker, JSP, Spring MVC, Spring Webflow.
-Expertise in Software Architecture and Framework design.

Comments and Discussions

GeneralMy vote of 5 Pin
kdgupta8724-Jan-11 9:12
Memberkdgupta8724-Jan-11 9:12 
GeneralDate validation Pin
kryzchek21-Aug-08 8:29
Memberkryzchek21-Aug-08 8:29 
GeneralRe: Date validation Pin
Sowkot Osman21-Aug-08 9:16
MemberSowkot Osman21-Aug-08 9:16 
GeneralNice Work Pin
Aslesh21-Aug-08 2:45
MemberAslesh21-Aug-08 2:45 
GeneralRe: Nice Work Pin
Sowkot Osman21-Aug-08 9:22
MemberSowkot Osman21-Aug-08 9:22 
GeneralRe: Nice Work Pin
Aslesh21-Aug-08 9:35
MemberAslesh21-Aug-08 9:35 
GeneralGood Job !! Pin
Abhijit Jana20-Aug-08 22:58
professionalAbhijit Jana20-Aug-08 22:58 
General[Message Removed] Pin
Mojtaba Vali13-Aug-08 17:53
MemberMojtaba Vali13-Aug-08 17:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.