Validation Controls In ASP.NET

Why do we use validation controls in ASP.NET?

Validation controls are an essential part of ASP.NET web development because they help ensure the integrity of user input. When users enter information into web forms, there is always the potential for intentional or unintentional errors. Validation controls provide a way to check the accuracy and validity of user input before the web application processes it.

Some of the reasons why validation controls are important in ASP.NET are:

  • Preventing invalid data from being submitted: Validation controls can check for required fields, format and type of data, and other criteria that must be met before the data can be submitted to the server. This helps ensure that the data is accurate and complete and that the application can process it correctly.
  • Improving user experience: When users enter invalid data, they may receive error messages or other feedback that helps them correct their mistakes. This can help prevent frustration and improve the overall user experience.
  • Enhancing security: Validation controls can help prevent malicious code or other attacks that could harm the web application or its users. For example, validation controls can check for potentially dangerous input such as SQL injection or cross-site scripting (XSS) attacks.
  • Meeting business requirements: Many businesses have specific rules and requirements for data entry, such as a minimum or a maximum number of characters or certain formatting conventions. Validation controls can help ensure that these requirements are met.

Overall, validation controls are important for ensuring the accuracy, completeness, and security of user input in ASP.NET web applications. In this article, learn what validation controls are in ASP.NET and how to use them in your web application.

In ASP.NET, the validation controls are used to validate the user input data, such as data format, data type, and date range. Some of the examples where validation controls can be used are:

  1. For example, a customer name text box does not start with a number or take any number.
  2. A patient's age does not take any non-number value and does not take a number more than 120. So I don't think a person's age can be more than 125.
  3. A date field does not take any nondate value and is most likely to provide a calendar control to select a date.
  4. A date range does not take any value based on business rules. So, for example, if the date is 'from' to 'to', ensure the value of the 'to' field is greater than that of the 'from' field. 
  5. A ticket booking system does not allow tickets to be booked for the past date than today.
  6. Make sure the date and time format is based on the local timezone. 
  7. A password is masked and has a minimum number of eight characters.
  8. A required input field must not have an empty value.
  9. Any custom logic required by the business. For example, when applying for a license, the applicant's minimum age must be greater than sixteen. OR to apply for social security benefits or senior citizen programs, the applicant must be older than sixty-five. 

Client-side validation vs. server-side validation in ASP.NET

ASP.NET supports two types of validation controls: 

  1. Client-side validation controls
  2. Server-side validation controls

Client-side validation is good, but we must depend on browser and scripting language support. The client-side validation is done in the user's browser using JavaScript and another scripting. You can use client-side validation libraries such as WebUIValidation.js in .NET.

Server-side validation in ASP.NET is done in the C# code-behind, where the value of the user input is read and validated on the server. This process is time-consuming but provides better security and is easier to implement in ASP.NET. For example, if an app wants to check the date range, the date value will be read from ASP.NET in C#, and the C# code behind the validation method will be compared against the rules.

Validation Controls in ASP.NET

ASP.NET provides several types of validation controls that can be used to validate user input in web forms. Some of the common validation controls are:

  1. RequiredFieldValidation Control
  2. CompareValidator Control
  3. RangeValidator Control
  4. RegularExpressionValidator Control
  5. CustomValidator Control
  6. ValidationSummary

The below table describes the controls and their use.

Validation Control Description
RequiredFieldValidation This control ensures that a field is not left empty or blank. It can be used for textboxes, dropdown lists, checkboxes, and other input controls.
CompareValidator This control compares the value of one input control to another. It can validate passwords, confirm email addresses, and other scenarios where two values must match.
RangeValidator This control checks if a value falls within a specific range. For example, it can be used to validate a user's age, income, or date of birth.
RegularExpressionValidator This control checks if a value matches a specified regular expression pattern. For example, it can validate email addresses, phone numbers, zip codes, and other input types.
CustomValidator This control allows developers to define their validation logic. It usually depends on the business rules. 
ValidationSummary This control displays a report of all validation errors that occurred on a Web page.

All validation controls are rendered in the form of <span> (labels are referred to as <span> on the client by the server)

Important points for validation controls

  • ControlToValidate property is mandatory for all validate controls.
  • One validation control will validate only one input control, but multiple validation control can be assigned to the input control.

The CausesValidation Property

Usually, validation is invoked in response to user actions like clicking submit button or entering data. For example, suppose you wish to perform validation on the page when the user clicks submit button.

In ASP.NET, the CausesValidation property is a boolean property used to determine whether the validation controls on a web form should be executed when the control with this property is clicked or otherwise activated. When CausesValidation is set to true, validation will be performed on the input provided by the user before any further processing of the control occurs.

For example, if a user clicks a button with CausesValidation set to true, any validation controls on the page associated with the input fields will be triggered. If any of these validations fail, the user will be notified with an error message, and the server-side processing of the button click will not be executed.

On the other hand, if CausesValidation is set to false, the validation controls will not be executed, and the control will be processed immediately without any validation.

In ASP.NET, the Validate() method triggers the validation controls on a web form and validates user input. This method is typically called in response to a user action, such as clicking a button or submitting a form, to ensure that the input provided by the user is valid before further processing occurs.

When the Validate() method is called, it causes all validation controls on the page to be executed, and their associated validation logic is run against the user input. If errors are found, the validation control will set its IsValid property to false, displaying the error message to the user.

The following code sets the CauseValidation property to true for the submit button on a page:

<asp:Button ID="Button2" runat="server" Text="Submit" CausesValidation=true />

Let's understand validation controls one by one with a practical demonstration:

ASP.NET RequiredFieldValidation Control

The RequiredFieldValidator control is simple validation control that checks to see if the data is entered for the input control. You can have a RequiredFieldValidator control for each form element you wish to enforce the mandatory field rule. It has properties 

<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
Style="top: 98px; left: 367px; position: absolute; height: 26px; width: 162px" 
ErrorMessage="password required" ControlToValidate="TextBox2">
</asp:RequiredFieldValidator> 

Here is the detailed article on RequiredFieldValidator Control in ASP.NET.

ASP.NET CompareValidator Control

The CompareValidator control allows you to make comparisons to compare data entered in an input control with a constant value or a value in a different control.

It can most commonly be used when you need to confirm the password entered by the user at registration time. The data is always case-sensitive.

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 145px;  
        left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"  
        ControlToValidate="TextBox3"></asp:RequiredFieldValidator>  

Here is the detailed article on Compare Validator Sample in ASP.NET MVC.

ASP.NET RangeValidator Control

The RangeValidator Server Control is another validator control that checks to see if a control value is within a valid range. The attributes necessary for this control are MaximumValue, MinimumValue, and Type.

<asp:RangeValidator ID="RangeValidator1" runat="server" 
Style="top: 194px; left: 365px; position: absolute; height: 22px; width: 105px" 
ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumValue="100" MinimumValue="18" Type="Integer"></asp:RangeValidator>  

Here is the detailed article on Range Validator In ASP.NET.

ASP.NET RegularExpressionValidator Control

A regular expression is a powerful pattern matching language that can identify simple and complex characters' sequences that would otherwise require writing code.

Using RegularExpressionValidator server control, you can check a user's input based on a pattern you define using a regular expression.

It is used to validate complex expressions. These expressions include a phone number, email address, zip code, etc. Using a RegularExpressionValidator is very simple. Set the ValidationExpression property to any expression you want, and it will validate it.

You can create your custom one if you don't find your desired regular expression.

In the example, I have checked the email id format:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Style="top: 234px;  
        left: 366px; position: absolute; height: 22px; width: 177px"   
        ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox5"   
        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>  

The complete code for the above four controls is as follows,

Default.aspx Design

validationcontrols_gui.gif

Default.aspx Source code

<%@ 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>  
        <asp:Label ID="Label3" runat="server" Style="top: 241px; left: 70px; position: absolute;  
            height: 22px; width: 128px; bottom: 282px;" Text="Enter your email id:"></asp:Label>  
        <asp:Label ID="Label1" runat="server" Style="top: 54px; left: 74px; position: absolute;  
            height: 22px; width: 128px" Text="Enter your name:"></asp:Label>  
        <asp:TextBox ID="TextBox1" runat="server" Style="top: 54px; left: 221px; position: absolute;  
            height: 22px; width: 128px; right: 396px;"></asp:TextBox>  
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Style="top: 56px;  
            left: 378px; position: absolute; height: 22px; width: 128px" ErrorMessage="RequiredFieldValidator"  
            ControlToValidate="TextBox1">name is   
        mandatory </asp:RequiredFieldValidator>  
    </div>  
    <p>  
        <asp:Button ID="Button1" runat="server" Style="top: 311px; left: 267px; position: absolute;  
            height: 26px; width: 61px" Text="Submit" />  
    </p>  
    <asp:TextBox ID="TextBox3" runat="server" Style="top: 145px; left: 217px; position: absolute;  
        height: 22px; width: 131px" TextMode="Password"></asp:TextBox>  
    <p>  
        <asp:TextBox ID="TextBox2" runat="server" Style="top: 101px; left: 218px; position: absolute;  
            height: 22px; width: 131px" TextMode="Password"></asp:TextBox>  
        <asp:Label ID="Label4" runat="server" Style="top: 105px; left: 74px; position: absolute;  
            height: 22px; width: 128px" Text="Password"></asp:Label>  
        <asp:TextBox ID="TextBox5" runat="server" Style="top: 239px; left: 210px; position: absolute;  
            height: 22px; width: 134px"></asp:TextBox>  
    </p>  
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Style="top: 98px;  
        left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"  
        ControlToValidate="TextBox2"></asp:RequiredFieldValidator>  
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 145px;  
        left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"  
        ControlToValidate="TextBox3"></asp:RequiredFieldValidator>  
    <asp:CompareValidator ID="CompareValidator1" runat="server" Style="top: 149px; left: 512px;  
        position: absolute; height: 26px; width: 162px" ErrorMessage="CompareValidator"  
        ControlToValidate="TextBox3" ValueToCompare="hello"></asp:CompareValidator>  
    <p>  
        <asp:Label ID="Label5" runat="server" Style="top: 148px; left: 71px; position: absolute;  
            height: 22px; width: 128px; bottom: 375px;" Text="Confirm Password"></asp:Label>  
        <asp:TextBox ID="TextBox4" runat="server" Style="top: 194px; left: 212px; position: absolute;  
            height: 22px; width: 140px"></asp:TextBox>  
        <asp:Label ID="Label6" runat="server" Style="top: 194px; left: 71px; position: absolute;  
            height: 22px; width: 128px; bottom: 329px;" Text="Enter your age:"></asp:Label>  
    </p>  
    <asp:RangeValidator ID="RangeValidator1" runat="server" Style="top: 194px; left: 365px;  
        position: absolute; height: 22px; width: 105px" ErrorMessage="RangeValidator"  
        ControlToValidate="TextBox4" MaximumValue="100" MinimumValue="18" Type="Integer"></asp:RangeValidator>  
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Style="top: 234px;  
        left: 366px; position: absolute; height: 22px; width: 177px"   
        ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox5"   
        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>  
    </form>  
</body>  
</html>

 

ASP.NET CustomValidator Control

What if there is no validator control that matches your need? In that case, you can use the CustomValidator control. The CustomValidator control in ASP.NET allows you to create your own custom logic to validate user data. 

The CustomValidator Control can be used on the client side and server side. JavaScript is used for client validation; you can use any .NET language to do server-side validation. Ib this example, I use the server-side CustomValidator. 

To write CustomValidator on the server side, you override the ServerValidate event.

customervalidator_gui.gif

Source Code

<%@ 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>  
        <asp:Label ID="Label1" runat="server" Text="User ID:"></asp:Label>  
 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"   
            ControlToValidate="TextBox1" ErrorMessage="User id required"></asp:RequiredFieldValidator>   
    
        <asp:CustomValidator ID="CustomValidator1" runat="server" OnServerValidate="UserCustomValidate"  
            ControlToValidate="TextBox1"   
            ErrorMessage="User ID should have atleast a capital, small and digit and should be greater than 5 and less  
than 26 letters"   
            SetFocusOnError="True"></asp:CustomValidator>  
        </div>  
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />  
    </form>  
</body>  
</html>

Code behind file

using System;  
using System.Configuration;  
using System.Data;  
using System.Linq;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.HtmlControls;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Xml.Linq;  
  
public partial class _Default : System.Web.UI.Page  
{  
    protected void UserCustomValidate(object source, ServerValidateEventArgs args)  
    {  
        string str = args.Value;  
        args.IsValid = false;  
       //checking for input length greater than 6 and less than 25 characters  
        if (str.Length < 6 || str.Length > 25)  
        {  
            return;  
        }  
        //checking for a atleast a single capital letter  
        bool capital = false;  
        foreach (char ch in str)  
        {  
            if (ch >= 'A' && ch <= 'Z')  
            {  
                capital = true;  
                break;  
            }  
        }  
        if (!capital)  
        {  
            return;  
        }  
       //checking for a atleast a single lower letter  
        bool lower = false;  
         foreach (char ch in str)  
        {  
            if (ch >= 'a' && ch <= 'z')  
            {  
                lower = true;  
                break;  
            }  
        }  
        if (!lower)  
        {  
            return;  
        }  
        bool digit = false;  
        foreach (char ch in str)  
        {  
            if (ch >= '0' && ch <= '9')  
            {  
                digit = true;  
                break;  
            }  
        }  
         if (!digit)  
        {  
            return;  
        }  
        args.IsValid = true;  
    }  
    protected void Page_Load(object sender, EventArgs e)  
    {  
    }  
   protected void Button1_Click(object sender, EventArgs e)  
    {  
    }  
}

customervalidator_output.gif

The server-side validation you write does not need to provide the same validation as the client-side validation. For example, the client-side validation can check for the user input data for range and type, and the server-side validation can check for data matching with the database. Both server-side and client-side validation can be used for a total solution.

ASP.NET ValidationSummary Control

ASP.NET has provided an additional control that complements the validator controls.

The ValidationSummary control is reporting control used by the other validation controls on a page. You can use this validation control to consolidate error reporting for all the validation errors on a page instead of leaving this up to every individual validation control.

The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list.

<asp:ValidationSummary ID="ValidationSummary1" runat="server"   
        style="top: 390px; left: 44px; position: absolute; height: 38px; width: 625px" /> 

Both ErrorMessage and Text properties are used to display error messages. However, text error messages have precedence.

If you are using ValidationSummary, only ErrorMessage and Text properties are used.

The complete code for the above ValidationSummary is as follows:

Default.aspx Design

validationSummary_design.gif

Default.aspx Source code

<%@ 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>  
        <asp:Label ID="Label1" runat="server" Style="top: 239px; left: 75px; position: absolute;  
            height: 22px; width: 128px" Text="Enter your Age:"></asp:Label>  
           
        <asp:Label ID="Label2" runat="server" Style="top: 94px; left: 81px; position: absolute;  
            height: 22px; width: 128px" Text="Enter your name:"></asp:Label>  
    </div>  
    <asp:TextBox ID="TextBox1" runat="server" Style="top: 95px; left: 250px; position: absolute;  
        height: 22px; width: 128px"></asp:TextBox>  
    <p>  
        <asp:TextBox ID="TextBox4" runat="server" Style="top: 195px; left: 249px; position: absolute;  
            height: 22px; width: 127px"></asp:TextBox>  
    </p>  
    <p>  
        <asp:Label ID="Label3" runat="server" Style="top: 148px; left: 76px; position: absolute;  
            height: 22px; width: 128px" Text="Enter Password:"></asp:Label>  
    </p>  
    <p>  
        <asp:TextBox ID="TextBox3" runat="server" Style="top: 146px; left: 249px; position: absolute;  
            height: 22px; width: 127px" TextMode="Password"></asp:TextBox>  
    </p>  
   <p>  
        <asp:Label ID="Label4" runat="server" Style="top: 197px; left: 75px; position: absolute;  
            height: 22px; width: 128px" Text="Confirm Password:"></asp:Label>  
    </p>  
    <asp:TextBox ID="TextBox2" runat="server" Style="top: 236px; left: 250px; position: absolute;  
        height: 22px; width: 127px" TextMode="Password"></asp:TextBox>  
    <asp:CompareValidator ID="CompareValidator1" runat="server" Style="top: 197px; left: 522px;  
        position: absolute; height: 22px; width: 17px" ErrorMessage="CompareValidator"  
        ControlToCompare="TextBox2" ControlToValidate="TextBox3">*</asp:CompareValidator>  
    <p>  
        <asp:Button ID="Button1" runat="server" Style="top: 333px; left: 248px; position: absolute;  
            height: 26px; width: 56px" Text="Submit" />  
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Style="top: 196px;  
            left: 393px; position: absolute; height: 22px; width: 22px" ErrorMessage="Confirm Password mandatory & should match password"  
            ControlToValidate="TextBox3">*</asp:RequiredFieldValidator>  
        <asp:RangeValidator ID="RangeValidator1" runat="server" Style="top: 235px; left: 388px;  
            position: absolute; height: 22px; width: 156px; bottom: 288px;" ErrorMessage="age between 18-100"  
            ControlToValidate="TextBox4" MaximumValue="100" MinimumValue="18" Type="Integer">*</asp:RangeValidator>  
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 92px;  
            left: 393px; position: absolute; height: 22px; width: 156px" ErrorMessage="Name is required"  
            ControlToValidate="TextBox1">*</asp:RequiredFieldValidator>  
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Style="top: 146px;  
            left: 391px; position: absolute; height: 22px; width: 156px" ErrorMessage="Password mandatory"  
            ControlToValidate="TextBox2">*</asp:RequiredFieldValidator>  
    </p>  
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" Style="top: 390px;  
        left: 44px; position: absolute; height: 38px; width: 625px" />  
    </form>  
</body>  
</html> 

The output of the ValidationSummary program

validationSummary.gif

Conclusion

I hope this article has helped you understand the Validation Controls in ASP.NET. Please share it if you know more about this article. Your feedback and constructive contributions are welcome. 


Similar Articles