ASP.NET

Custom Validator Control in ASP.NET

To begin with, in this article, I will explain Custom Validator Control in ASP.NET using an example. Although ASP.NET provides a number of validation controls, still in many situations none of them may work. Especially, when you want to match the content of a TextBox with a value stored in the database, you need a user-defined function for this purpose.

Likewise, if the input value should match with a list or collection of pre-defined values, we can’t use any of the existing validation controls. Hence, we need a custom validation method.

CustomValidator in ASP.NET

In order to perform a custom validation, the ASP.NET provides CustomValidator control. Also, it is a server-side validation control. Therefore, the validation is performed at the server. Hence, proper client-side validation should be there on the page before data is sent to the server for validation.

Properties of CustomValidator Control

The following properties are important for defining custom validation method.

Properties

Evidently, the CustomValidator control has a ControlToValidate property that indicates which input of which control is being validated. Whenever the server performs validation, the ServerValidate event occurs and it creates an object of ServerValidateEventArgs. Further, this object has two properties – Value, and IsValid.

While the Value property contains the string that is being validated, the IsValid property is a boolean property. In case, the Value passes the validation, the IsValid property gets a true value. Otherwise, it gets a false value indicating that the validation has failed.

Further, the OnServerValidate property indicates the name of the method that performs the validation.

It is important to note that for using a CustomValidator, you need not use the ControlToValidate property. In fact, it is possible to use this control for server-side validation when data is not used from an input control. Also, this control can be used for client-side validation.

Example of Custom Validator Control

The following ASPX file contains a CustomValidator control that validated the input of TextBox1. As can be seen, it uses a function called ValidateCourse that we assign to the OnServerValidate property. Basically, the following example requires the user to enter the name of a course as input. Accordingly, the user has two choices – BCA, and MCA. Whenever the user enters any other value, the string assigned in the Text property should be displayed. Moreover, the ErrorMessage property contains the error message value for a ValidationSummary control.

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CustomValidatorExamples.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <br />
            Enter the name of a course<br />
            that you want to pursue [MCA, BCA]:<br />
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:CustomValidator ID="cv1" runat="server" 
                ErrorMessage="Validation Errors"
                 Text="Enter a Valid course Name"
                 ControlToValidate="TextBox1"
                  Display="Static"
                 OnServerValidate="ValidateCourse"></asp:CustomValidator>
            <br />
        </div>
    </form>
</body>
</html>

After that, we define the ValidateCourse() method in the Code Behind. Likewise, the parameter args is an object of type ServerValidateEventArgs class. Hence, it provides the value to validate. Accordingly, the method retrieves the Value in a string variable and compares it with particular values. Also, it updates the IsValid property to indicate the result of validation.

WebForm1.aspx.cs

using System;
using System.Web.UI.WebControls;

namespace CustomValidatorExamples
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void ValidateCourse(object source, ServerValidateEventArgs args)
        {
            try
            {
                String str = args.Value;
                str = str.Trim();
                if (str.Equals("MCA") || str.Equals("BCA"))
                    args.IsValid = true;
                else
                    args.IsValid = false;
            }
            catch(Exception ex)
            {
                args.IsValid = false;
            }
        }

    }
}

Output

Custom Validator Control in ASP.NET
Custom Validator Control in ASP.NET

Summary

To sum up, custom validation is useful when we want to perform validation according to user-defined criteria. Therefore, it requires creating a method that performs validation. Further, the name of this validation method is assigned to the OnServerValidate property of the CustomValidator control.




Related Topics

A Brief Overview of Laravel

Examples of AdRotator Control in ASP.NET

Overview of MVC architecture in ASP.NET

Binding Data to Web Control in ADO.NET

Examples of Validation Controls in ASP.NET

Data Binding Using BulletedList Control

Validation Summary Control in ASP.NET

An Example of Data Binding with RadioButtonList Control

Validation Controls Examples – RequiredFieldValidator, CompareValidator, and RangeValidator

Leave a Reply

Your email address will not be published. Required fields are marked *