Tuesday, March 11, 2014

Asp.NET Validation - CustomValidator

The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation.

The client side validation is accomplished through the ClientValidationFunction property. The client side validation routine should be written in a scripting language, like JavaScript or VBScript, which the browser can understand.

The server side validation routine must be called from the control.s ServerValidate event handler. The server side validation routine should be written in any .Net language, like C# or VB.Net.

Example:-
Default.aspx :-


<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter Text :
        <asp:TextBox runat="server" id="txtCustom" />
        <asp:CustomValidator
            runat="server" id="cv" controltovalidate="txtCustom"
            onservervalidate="cv_ServerValidate"
            errormessage="The text must be exactly 8 characters long!"
            BackColor="#009900" ForeColor="White" />
        <br /><br />
    </div>
    </form>
</body>
</html>

in Default.aspx.cs :-


protected void cv_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        if (e.Value.Length == 8)
            e.IsValid = true;
        else
            e.IsValid = false;
    }

Output:


No comments:

Post a Comment