Performing Validations with ASP.NET�Part 2 of 2

In the previous article, you learned how to perform validations using CompareValidator, CustomValidator and RangeValidator provided with the .NET Framework. In this second part, I will examine the applications of remaining three controls namely RegularExpressionValidator, RequiredFieldValidator and ValidationSummary. While the ValidationSummary control summarizes all the errors occurred, the remaining two controls are used in different circumstances in a project depending upon the requirements.

RegularExpressionValidator

This validation control is used to parse strings using special characters. This is similar to the concept of Pattern Matching in PERL. This control can be used in situations such as:

  • To check for "@" character on an e-mail address (See Listing 1)
  • To verify whether the user entered valid Zip code, Telephone number and web address.

Listing - 1

[Visual Basic .NET]

<%@ Page Language="VB" %>
<html>
<head>
    <title>Validation Controls in Action</title>
</head>
<body>
    <form runat="server">
        <p>
            Enter your e-mail address:  
        </p>
        <p>
            <asp:TextBox id="TextBox1" runat="server">
            </asp:TextBox>
            
            <asp:Button id="Button1" runat="server" 
            Text="Click here">
            </asp:Button>
        </p>
        <p>
            <asp:RegularExpressionValidator 
            id="RegularExpressionValidator1" 
            runat="server" 
 ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
            ErrorMessage="Please enter a valid E-mail ID" 
            ControlToValidate="TextBox1">
            </asp:RegularExpressionValidator>
        </p>
    </form>
</body>
</html>

[C#]

<%@ Page Language="C#" %>
<html>
<head>
    <title>Validation Controls in Action
</head>
<body>
    <form runat="server">
        <p>
            Enter your e-mail address:  
        </p>
        <p>
            <asp:TextBox id="TextBox1" runat="server">
            </asp:TextBox>
            
            <asp:Button id="Button1" runat="server" 
            Text="Click here">
            </asp:Button>
        </p>
        <p>
            <asp:RegularExpressionValidator 
            id="RegularExpressionValidator1" 
            runat="server" 
 ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
            ErrorMessage="Please enter a valid E-mail ID" 
            ControlToValidate="TextBox1">
            </asp:RegularExpressionValidator>
        </p>
    </form>
</body>
</html>

It is the ValidationExpression property shown in the above listings that makes the application work. Hit the click here button without entering the @ symbol and observe the output (see Figure 1). The interesting point to note is that even if you enter @ symbol, it would still show errors, till you fill out the full domain part (like yahoo.com) of the email address. It is these powerful capabilities that made this control the most popular among .NET developers and communities.

Figure 1

If you want to validate an Internet URL, simply update the ValidationExpression property in the above code with the listing as shown below:

Listing 2

http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

Moreover, you can also write custom validation statements depending upon your project requirements.

TIP: You can easily generate the code for the ValidationExpression property with the help of Visual Studio .NET or ASP.NET WebMatrix. Simply place the control from the Toolbox and press F4 to get the properties window. From the window, move down until you see the ValidationExpression property and click the small ellipsis button on the extreme right to open the Regular Expression Editor window. From this window, you can select your choice to get predefined expression statements for a number of items.

RequiredFieldValidator

As the name denotes, this control is used in cases where a user should compulsorily enter a value, preferably in a textbox. Prior to .NET, this kind of functionality was achieved through complex JavaScript and VBScript functions. Enter the code given in the listing given below, execute and observe the result:

Listing - 3

[Visual Basic .NET]

<%@ Page Language="VB" %>
<html>
<head>
</head>
<body>
    <form runat="server">
        <p>
            Your Name: 
        </p>
        <p>
            <asp:TextBox id="TextBox1" runat="server">
            </asp:TextBox>
            
            <asp:Button id="Button1" runat="server" Text="Click here">
            </asp:Button>
        </p>
        <p>
            <asp:RequiredFieldValidator 
            id="RequiredFieldValidator1" 
            runat="server" 
            ErrorMessage="The above field should not be left blank" 
            ControlToValidate="TextBox1" 
            display="static">
            </asp:RequiredFieldValidator>
        </p>
    </form>
</body>
</html>

[C#]

<%@ Page Language="C#" %>
<html>
<head>
</head>
<body>
    <form runat="server">
        <p>
            Your Name: 
        </p>
        <p>
            <asp:TextBox id="TextBox1" runat="server">
            </asp:TextBox>
            
            <asp:Button id="Button1" runat="server" Text="Click here">
            </asp:Button>
        </p>
        <p>
            <asp:RequiredFieldValidator 
            id="RequiredFieldValidator1" 
            runat="server" 
            ErrorMessage="The above field should not be left blank" 
            ControlToValidate="TextBox1" 
            display="static">
            </asp:RequiredFieldValidator>
        </p>
    </form>
</body>
</html>

Validation Summary

With the help of this control, you can display the error messages on a page. It collects all the error messages from the enabled controls and shows them in various ways like list, bulleted list, and single paragraph (See Figure 2). It also displays the errors in a message box. The code shown in listing 4 examines the application of this control:

Listing - 4

[Visual Basic .NET]

<%@ Page Language="vb" %>
<html>
<head>
</head>
<body>
    <form runat="server">
        <p>
            Enter a first value: 
            
            <asp:TextBox id="txtValue1" runat="server">
            </asp:TextBox>
            
            <asp:RequiredFieldValidator id="Reqfield1" 
            runat="server" 
            ErrorMessage="The above field should not be left blank" 
            ControlToValidate="txtValue1">
            </asp:RequiredFieldValidator>
        </p>
        <p>
            Enter a second value: 
            
            <asp:TextBox id="txtValue2" runat="server">
            </asp:TextBox>
            
            <asp:RequiredFieldValidator id="reqField2" 
            runat="server" 
            ErrorMessage="The above field should not be left blank" 
            ControlToValidate="txtValue2">
            </asp:RequiredFieldValidator>
        </p>
        <p>
            <asp:Button id="btnClick" runat="server" Text="Click Here">
            </asp:Button>
        </p>
        <p>
            <asp:ValidationSummary id="Validsummary" 
            runat="server" HeaderText="Errors are as follows:" 
            ShowMessageBox="True">
            </asp:ValidationSummary>
        </p>
    </form>
</body>
</html>

As mentioned above, the above listing also displays a message box upon execution since the ShowMessageBox property is set to true.



Figure 2 - Click here for larger image

[C#]

<%@ Page Language="C#" %>
<html>
<head>
</head>
<body>
    <form runat="server">
        <p>
            Enter a first value: 
            
            <asp:TextBox id="txtValue1" runat="server">
            </asp:TextBox>
            
            <asp:RequiredFieldValidator id="Reqfield1" 
            runat="server" 
            ErrorMessage="The above field should not be left blank" 
            ControlToValidate="txtValue1">
            </asp:RequiredFieldValidator>
        </p>
        <p>
            Enter a second value: 
            
            <asp:TextBox id="txtValue2" runat="server">
            </asp:TextBox>
            
            <asp:RequiredFieldValidator id="reqField2" 
            runat="server" 
            ErrorMessage="The above field should not be left blank" 
            ControlToValidate="txtValue2">
            </asp:RequiredFieldValidator>
        </p>
        <p>
            <asp:Button id="btnClick" runat="server" Text="Click Here">
            </asp:Button>
        </p>
        <p>
            <asp:ValidationSummary id="Validsummary" 
            runat="server" HeaderText="Errors are as follows:" 
            ShowMessageBox="True">
            </asp:ValidationSummary>
        </p>
    </form>
</body>
</html>

From the above discussion, it is clear that all the required stuffs for validating Graphical User Interface (GUI) controls is now available under a single umbrella of Microsoft .NET. Once you learned the usage of all the controls, it is very easy to implement them, be it a WinForm or an ASP.NET WebForm.

About the Author

Anand Narayanaswamy is a Microsoft MVP (Microsoft Most Valuable Professional) who works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, Software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials. You can catch him at anandnswamy@rediffmail.com.



About the Author

Anand Narayanaswamy

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Comments

  • General ASP.NET - Table of Contents

    Posted by Legacy on 05/01/2003 12:00am

    Originally posted by: Ram

    http://www.codeguru.com/net_asp/validating2.html
    
    

    Hi,
    In breif for beginners the article is very nice... a small doubt if possible pls aswer...
    If we got two input boxes and two buttons on the same page onclicking of first button validation has to happen to the first input box & the same way if i click on second button second field should get validate... how do i achive this...

    thank you

    -Ramana

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: October 23, 2014 @ 12:00 p.m. ET / 9:00 a.m. PT Despite the current "virtualize everything" mentality, there are advantages to utilizing physical hardware for certain tasks. This is especially true for backups. In many cases, it is clearly in an organization's best interest to make use of physical, purpose-built backup appliances rather than relying on virtual backup software (VBA - Virtual Backup Appliances). Join us for this eSeminar to learn why physical appliances are preferable to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds