Search This Blog

Sunday, August 19, 2012

ASP.NET CustomValidator Control for password validation



CustomValidator - Checks the form field's value against custom validation logic that you, the developer, provide.All validation logic create by own.

when text box value blank then call RequiredFieldValidator

when text box value not match with condition CustomValidator

All validation fulfill for text box.

ASPX page code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="SBIWEB.WebForm3" %>

<!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>askdotnet</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txt_password" runat="server" class="style2" MaxLength="50"></asp:TextBox>
        <asp:Image ID="Image1" runat="server" Visible="false" ImageUrl="~/images/chk.jpg" />
        <asp:Image ID="Image2" runat="server" Visible="false" ImageUrl="~/images/cute_ball_stop.png" />
        <asp:CustomValidator ID="CustomValidator1" ControlToValidate="txt_password" runat="server"
            ErrorMessage="Please enter 6 digit password." 
            OnServerValidate="CustomValidator1_ServerValidate" Font-Italic="True" 
            Font-Overline="True" Font-Strikeout="False" Font-Underline="True"></asp:CustomValidator>
        <br />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txt_password"
            runat="server" ErrorMessage="Please enter value." Font-Italic="True" 
            Font-Overline="True" Font-Underline="True"></asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
    </div>
    </form>
</body>
</html>

cs page code:

using System;
using System.Collections;
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;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Page.Validate();
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs e)
        {
            if (e.Value.Length == 6)
            {
                e.IsValid = true;
                Image1.Visible = true;
                Image2.Visible = false;
            }
            else
            {
                e.IsValid = false;
                Image1.Visible = false;
                Image2.Visible = true;
            }
        }

    }
}





No comments :