articles

Home / DeveloperSection / Articles / Validation Control in ASP.Net

Validation Control in ASP.Net

Sumit Kesarwani4876 16-May-2013

In this article, I’m trying to explain the concept of input validation and its types in asp.net and how to implement them in your application.

Whenever we have an application that expects user input, then it becomes important to ensure the validity of the data input by the user. We might have scenarios when some data is mandatory for the user to enter. There are scenarios when the user data has to be in some particular format example email ID. There could be scenarios when we want the data to be in some range example date input.

So for all the above mentioned scenarios, if we take the user input without validation, then chances are that we will end up having wrong data with us (perhaps in database). If it is a bad day for us then possibly our application might also end up behaving in an unexpected manner and even crash on us (like if we try to convert a non-numeric  string to int). Worst case scenario, the user will use the input field to perform SQL injection and cause serious damage to our database. So it is always a good idea to have validation in place whenever we are taking input from the user.

Types of Validation

There are two ways we can perform validation:

  •       Client side validation
  •       Server side validation
Client Side Validation

Client side validation is something that will happen on users' browser. The validation will occur before the data gets posted back to server. It is a good idea to have client side validation as the user gets to know what needs to be changed immediately, i.e., no trips to servers are made. So from the users' point of view, it gives him fast response and from the developers' point of view, it saves valuable resources of server.

Server Side Validation

Server side validation occurs at server. The benefit of having server side validation is that if the user somehow bypasses the client side validation (accidentally or deliberately), then we can catch the problem on the server side. So having server side validation provides more security and ensures that no invalid data gets processed by the application.

Validation Controls in ASP.NET

The validation controls provided by ASP.NET are

1.      RequiredFiledValidator

2.      CompareValidator

3.      RangeValidator

4.      RegularExpressionValidator

5.      CustomValidator 

RequiredFieldValidator

This validation control will be used when we are mandating the user input for any particular field. Let's say we have a simple form with name field and we don't want this to be empty. so what we can do is add a RequiredFieldValidator to the page, set the ControlToValidate to the ID of the name input field, set the error message property. 

CompareValidator

This control will compare the value of its ControlToValidate with ControlToCompare. It uses the comparison operators to do the same. Now let us say we have a hypothetical scenario where we want the same name to be entered twice.

RangeValidator

In scenarios where we want to ensure that the value entered by the user is in some predefined range, we can use this control. Let us try to add this control on our page and use this to validate the age of the user. We are saying the valid age is between 18 to 50.

Regular Expression Validator

RegularExpressionValidator comes in handy when we want input data to be in some specific format. Let us try to do that on our page by asking the user for his email ID. We will be using the RegularExpressionValidator for validating the format of email id.

CustomValidator

If with all these validation controls provided by ASP.NET, we still find ourselves a scenario where we need customized validation behavior, we can use the CustomValidator Control. Let us try to use this control and perform custom client side as well as server side validation. What we will do is we will check for '-' character in user input and reject the input if '-' is present in any field (assuming a SQL injection attempt). 

Example
Step 1:-

Design a web form as shown below:

Validation Control in ASP.Net

WebForm1.aspx
<headrunat="server">


    <title></title>

    <scriptlanguage="javascript">

    functionvalidateName(source,arguments)

    {

        if(arguments.Value.search('-') !=-1)

        {

            arguments.IsValid=false;

        }

    }

    </script>

</head>

<body>

    <formid="form1"runat="server">

    <div>

        <table>

            <tr>

                <td>

                    Name

                </td>

                <td>

                    <asp:TextBoxID="txtName" runat="server"></asp:TextBox>

                    <asp:RequiredFieldValidatorID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter Name"

                        ControlToValidate="txtName" Display="Dynamic"></asp:RequiredFieldValidator>

                    <asp:CustomValidatorID="CustomValidator1" runat="server" ErrorMessage="'-' is not allowed"

                        ControlToValidate="txtName" Display="Dynamic" ClientValidationFunction="validateName"></asp:CustomValidator>

                </td>

            </tr>

            <tr>

                <td>

                    Name Again

                </td>

                <td>

                    <asp:TextBoxID="txtNameAgain" runat="server"></asp:TextBox>

                    <asp:RequiredFieldValidatorID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter Name"

                        ControlToValidate="txtNameAgain"Display="Dynamic"></asp:RequiredFieldValidator>

                    <asp:CompareValidatorID="CompareValidator1" runat="server" ErrorMessage="Name should be same in both the fields"

                        ControlToValidate="txtNameAgain"ControlToCompare="txtName" Display="Dynamic"></asp:CompareValidator>

 

                </td>

            </tr>

            <tr>

                <td>

                    Age

                </td>

                <td>

                    <asp:TextBoxID="txtAge" runat="server"></asp:TextBox>

                    <asp:RequiredFieldValidatorID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Age"

                        ControlToValidate="txtAge" Display="Dynamic"></asp:RequiredFieldValidator>

                    <asp:RangeValidatorID="RangeValidator1" runat="server" ErrorMessage="Age should be between 18 to 50"

                        ControlToValidate="txtAge" Display="Dynamic" MinimumValue="18"MaximumValue="50"></asp:RangeValidator>

                </td>

            </tr>

            <tr>

                <td>

                    Email ID

                </td>

                <td>

                    <asp:TextBoxID="txtEmail" runat="server"></asp:TextBox>

                    <asp:RequiredFieldValidatorID="RequiredFieldValidator4" runat="server" ErrorMessage="Enter Email ID"

                        ControlToValidate="txtEmail" Display="Dynamic"></asp:RequiredFieldValidator>

                    <asp:RegularExpressionValidatorID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid Format for Email"

                        ControlToValidate="txtEmail" ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"

                        Display="Dynamic">

                    </asp:RegularExpressionValidator>

                </td>

            </tr>

            <tr>

                <td>

                </td>

                <td>

                    <asp:ButtonID="btnSubmit" runat="server" Text="Submit"OnClick="btnSubmit_Click"/>

                </td>

            </tr>

        </table>

        <br/>

 

        <asp:Label ID="lblName"runat="server"></asp:Label>

        <br/>

 

        <asp:Label ID="lblAge"runat="server"></asp:Label>

        <br/>

 

        <asp:Label ID="lblEmail" runat="server"></asp:Label>

    </div>

    </form>

</body>

 WebForm1.aspx.cs

using System;

 
namespace InputValidationWebApplication
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgse)
        {
 
        }
 
        protected void btnSubmit_Click(objectsender, EventArgse)
        {
            lblName.Text=txtName.Text;
            lblAge.Text=txtAge.Text;
            lblEmail.Text=txtEmail.Text;
            txtName.Text="";
            txtNameAgain.Text="";
            txtAge.Text="";
            txtEmail.Text="";
        }
    }
}
Step 2:-

Run the application

Validation Control in ASP.Net

If you do not enter any values and click on submit button, you will get these error messages. This is the work of Required Field validator’s control.

Validation Control in ASP.Net

If you enter hyphen (-) in name field, then you will get this error. This is the work of Custom validator control.

Validation Control in ASP.Net

If the name in both the fields does not match, then you will get this error. This is the work of Compare validator control.

Validation Control in ASP.Net

If the age is not between ranges of 18 to 50, then you will get this error. This is the work of Range validator control.

Validation Control in ASP.Net

If the email id is not in valid format, then you will get this error. This is the work of Regular expression validator control.

Validation Control in ASP.Net

If all the values are filled correctly, then you will get this output.


Updated 07-Sep-2019

Leave Comment

Comments

Liked By