Click here to Skip to main content
15,884,836 members
Articles / Web Development / ASP.NET

How to Use the ASP.NET Validation Control to Validate the User Input

Rate me:
Please Sign up or sign in to vote.
3.83/5 (17 votes)
29 Dec 2009Ms-PL2 min read 171.6K   2K   21   4
How to use ASP.NET validation control to achieve a login module.

Introduction

ASP.NET Validation control is a series of controls which can help us to validate the user input and prevent the malicious data from being posted to the server easily. And according to the browser’s security limit, the ASP.NET Validation control provides two ways of validation: Server Side and Client Side. This article demonstrates how to use ASP.NET Validation controls in that two ways.

This is only partial of the ASP.NET samples in All-In-One Framework. You can get more samples from http://cfx.codeplex.com/.

Background

Microsoft All-In-One Code Framework delineates the framework and skeleton of Microsoft development techniques through typical sample codes in three popular programming languages (Visual C#, VB.NET, Visual C++). Each sample is elaborately selected, composed, and documented to demonstrate one frequently-asked, tested or used coding scenario.

Using the Code

Sample Scenario

In order to explain the Validation controls more clearly, the sample will simulate a user register module, it contains: email and password.

ASP.NET Validation Controls Basics

There are 6 controls included:

  • The RequiredFieldValidation Control
  • The CompareValidator Control
  • The RangeValidator Control
  • The RegularExpressionValidator Control
  • The CustomValidator Control

General properties:

  • ControlToValidate - This value is which control the validator is applied to.
  • ErrorMessage - This is the error message that will be displayed in the validation summary.

ClientValidation Sample

In this section, we will start our trip to use the Validation controls at the client side.

  1. Validate whether the username is email with the RegularExpressionValidator Control and make sure that a user inputs a value with RequiredFieldValidation Control.
    ASP.NET
    <asp:TextBox ID="tb_email" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
        ControlToValidate="tb_email" ErrorMessage="Required field cannot be left blank."
        Display="Dynamic">
    </asp:RequiredFieldValidator>
     
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
        ErrorMessage="Invalid email address."    ControlToValidate="tb_email" 
        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
        Display="Dynamic">
    </asp:RegularExpressionValidator>
  2. Use the CompareValidator to confirm new passwords.
    ASP.NET
    <asp:TextBox ID="tb_pwd" runat="server" TextMode="Password"></asp:TextBox>      
    <asp:TextBox ID="tb_repwd" runat="server" TextMode="Password"></asp:TextBox>    
    <asp:CompareValidator ID="CompareValidator1" runat="server" 
        ErrorMessage="Passwords do not match."    ControlToCompare="tb_repwd"
        ControlToValidate="tb_pwd">
    </asp:CompareValidator>
  3. In order to confirm that the length of the password is more than 6 characters, we can use the CustomValidator Control.
    JavaScript
            function ClientValidate(source, clientside_arguments) {
                //Test whether the length of the value is more than 6 characters
            if (clientside_arguments.Value.length >= 6) {
                clientside_arguments.IsValid = true;
            }
            else { clientside_arguments.IsValid = false };
    }
    ASP.NET
    <asp:TextBox ID="tb_pwd" runat="server" TextMode="Password"></asp:TextBox>  
           <asp:CustomValidator ID="CustomValidator1"
           ClientValidationFunction="ClientValidate"
           ControlToValidate="tb_pwd" runat="server"
           ErrorMessage="The password must be more than 6 characters."
           Display="Dynamic"></asp:CustomValidator>
  4. And collect all the error messages from all the invalid controls with the ValidationSummary control.
    ASP.NET
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

SeverValidation Sample

Sometimes, the client does not support client side validation, for example: the security level of the browser is very high, therefore we have to validate the input at the server side.

The following code snippet will demonstrate how to use the RequiredFieldValidator and CustomValidator at the server side.

.aspx file:

ASP.NET
<asp:TextBox ID="tb_username" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
        ControlToValidate="tb_username" Display="Dynamic" EnableClientScript="False"
        onload="RequiredFieldValidator1_Load">
</asp:RequiredFieldValidator>
        
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="tb_username" 
    runat="server" ErrorMessage="The username must be more than 6 characters."
    Display="Dynamic" onservervalidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>

.cs file:

C#
protected void RequiredFieldValidator1_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        //get which input TextBox will be validated.
        TextBox tx = (TextBox)this.FindControl(
            RequiredFieldValidator1.ControlToValidate);
        if (string.IsNullOrEmpty(tx.Text))
        {
            RequiredFieldValidator1.ErrorMessage =
                "Required field cannot be left blank.";
        }
    }
}

protected void CustomValidator1_ServerValidate(object source,
    ServerValidateEventArgs args)
{
    //Test whether the length of the value is more than 6 characters
    if (args.Value.Length >= 6)
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}

Points of Interest

If there is any problem, you can have a look at the ReadMe.txt file in each sample project, which contains a step by step tutorial of how to build the project.

If you want to get more samples, please visit Microsoft All-In-One Code Framework

    License

    This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


    Written By
    China China
    Microsoft All-In-One Code Framework delineates the framework and skeleton of Microsoft development techniques through typical sample codes in three popular programming languages (Visual C#, VB.NET, Visual C++). Each sample is elaborately selected, composed, and documented to demonstrate one frequently-asked, tested or used coding scenario based on our support experience in MSDN newsgroups and forums. If you are a software developer, you can fill the skeleton with blood, muscle and soul. If you are a software tester or a support engineer like us, you may extend the sample codes a little to fit your specific test scenario or refer your customer to this project if the customer's question coincides with what we collected.
    http://cfx.codeplex.com/

    Comments and Discussions

     
    GeneralMy vote of 2 Pin
    unlucky88684-Feb-15 17:56
    unlucky88684-Feb-15 17:56 
    Questionvalidation for text box Pin
    Member 107660458-Aug-14 21:58
    Member 107660458-Aug-14 21:58 
    Questionhow to check for spaces in compare validator Pin
    Warreer24-Apr-13 4:11
    Warreer24-Apr-13 4:11 
    GeneralMy vote of 2 Pin
    Sacha Barber30-Dec-09 2:59
    Sacha Barber30-Dec-09 2:59 
    average

    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.