How to use the ASP.NET Validation Control to validate the user input

 

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.

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 six 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: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: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.

<script type="text/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 };

    }

</script>

  <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: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: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:

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;

     }

        }

How to Get the Sample

For a complete demo, please refer to the sample named CSASPNETPageValidation in All-In-One Code Framework project at https://cfx.codeplex.com/.