How To Create your own CustomValidation Control In 2.0

how to derive your custom control from a base class and add your own features. In this article we'll demonstrate how to derive a class from the BaseValidtor class to create your own validator control. Why would you do this? Well, in short the validator controls collection is very good, but as you will find they don't cover every type of validation you will need to do. You can use the custom validtor control to accomidate this, but if you need to do validtation in multiple places within your web application or even multiple web applications and sites then this isn't such a good solution. Instead, I would recommend creating a custom validation control and using that - why? Because it's cleaner! As previously mentioned this is an example of a very simple control. This validator control is derived from the base class BaseValidator . There is one properties added to the BaseValidator Email and the contents of the ControlToValidator must be this values. EmailValidator.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace EmailValidator
 public class EmailValidator : BaseValidator
     protected string strEmail;

     public string Email

             strEmail = value;


     protected override bool EvaluateIsValid()
         string val = this.GetControlValidationValue(this.ControlToValidate);
         string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)
         System.Text.RegularExpressions.Match match =
Regex.Match(val.Trim(), pattern, RegexOptions.IgnoreCase);
         if (match.Success)

             return true;


             return false;



This method contains the code used to determine validity. The return value
is boolean. If false is returned then then the ControlToValidate will not
have a valid value; otherwise true.
This method gets the value associated with a specified INPUT control.
The return value is a string and it expects a parameter which should be the
ID of the INPUT control. You retrieve the INPUT controls ID property using the
following property

This property contains the ID property of the INPUT control the validation
control should validate.
How To Use create a new application in and add the below code in aspx page.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<%@ Register Assembly="EmailValidator" Namespace="EmailValidator" TagPrefix="ccl" %>
<html xmlns="">
<head id="Head1" runat="server">
  <title>Untitled Page</title>
  <form id="form1" runat="server">
          <asp:TextBox ID="txt" runat="server"></asp:TextBox>
          <ccl:EmailValidator ControlToValidate="txt" runat="server" ID="SS"
ErrorMessage="Envalid Email Address"
          <asp:Button ID="btn" runat="server" Text="Submit" />

Post a Comment


Close Menu