Click here to Skip to main content
6,595,854 members and growing! (17,181 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Beginner License: The Code Project Open License (CPOL)

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

By Sowkot Osman

Common Validation and Length Validation with Regular Expression in ASP.NET
C#, .NET, ASP.NET, Dev
Posted:13 Aug 2008
Updated:20 Aug 2008
Views:29,230
Bookmarked:41 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
12 votes for this article.
Popularity: 3.88 Rating: 3.59 out of 5
2 votes, 16.7%
1

2
2 votes, 16.7%
3
2 votes, 16.7%
4
6 votes, 50.0%
5

Introduction

Input validation is very common and important in any kind of application. In case of web application server side validation is a must and client side validation is highly anticipated. As you know 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.

In this article I'll provide an Util class full of some regular expressions for common input validation. The main attractive part is length validation of textarea control of html. As you know in case of textfield you can tell the max length of it. But for textarea you cannot do it. So normally we have to write some javascript function to check the length before form submit.

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

Yes, 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-_\\$]+(&" + 
               "[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 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" 
     "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>
            <h3>
                Validation Example</h3>
            <table border="1" width="50%">
                <tr>
                    <td style="width: 200px">
                        <asp:Label ID="CommentLabel" 
                            runat="server" Text="Comment:">
                        </asp:Label></td>
                    <td>
                        <asp:TextBox ID="CommentTextBox" runat="server" 
                             TextMode="MultiLine" Width="500px" />
                        <asp:RegularExpressionValidator ID="CommentValidator" 
                          runat="server" ControlToValidate="CommentTextBox">
                        </asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="DateLabel" runat="server" 
                           Text="Date:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="DateTextBox" 
                           runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="DateValidator" runat="server" 
                          ControlToValidate="DateTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="TimeLabel" runat="server" 
                          Text="Time:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="TimeTextBox" runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="TimeValidator" runat="server" 
                          ControlToValidate="TimeTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="NumberLabel" runat="server" 
                          Text="Number:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="NumberTextBox" runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="NumberValidator" runat="server" 
                          ControlToValidate="NumberTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="DigitLabel" runat="server" 
                          Text="Digit:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="DigitTextBox" runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="DigitValidator" runat="server" 
                          ControlToValidate="DigitTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="NonNegativeLabel" runat="server" 
                           Text="Non Negative:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="NonNegativeTextBox" runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="NonNegativeValidator" runat="server" 
                          ControlToValidate="NonNegativeTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="UrlLabel" runat="server" Text="Url:">
                        </asp:Label></td>
                    <td>
                        <asp:TextBox ID="UrlTextBox" runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="UrlValidator" runat="server" 
                          ControlToValidate="UrlTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

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;
    }
}

Screenshot

screenshot.jpg

Here the Url validator expression and message was need of my business requirement. If you have a different requirement then customize yours one.

License

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

About the Author

Sowkot Osman


Member
3 years of extensive experience in devloping both desktop and web applications in C#.NET, VB.NET and ASP.NET
2 year of experience in developing web application in J2EE, Free Marker, JSP, Spring MVC, Spring Webflow.
Expertise in Software Architecture and Framework design.
Blog: http://sowkot.blogspot.com


Occupation: Software Developer
Location: Bangladesh Bangladesh

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralDate validation Pinmemberkryzchek9:29 21 Aug '08  
GeneralRe: Date validation PinmemberSowkot Osman10:16 21 Aug '08  
GeneralNice Work PinmemberSanthapur3:45 21 Aug '08  
GeneralRe: Nice Work PinmemberSowkot Osman10:22 21 Aug '08  
GeneralRe: Nice Work PinmemberSanthapur10:35 21 Aug '08  
GeneralGood Job !! PinmemberAbhijit Jana23:58 20 Aug '08  
General[Message Removed] PinmemberMojtaba Vali18:53 13 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 Aug 2008
Editor: Smitha Vijayan
Copyright 2008 by Sowkot Osman
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project