Click here to Skip to main content
15,895,746 members
Articles / Web Development / ASP.NET

Exploring ASP.NET Validators

Rate me:
Please Sign up or sign in to vote.
4.91/5 (41 votes)
9 Apr 2010CPOL19 min read 182.2K   1.8K   123  
This article digs deep into ASP.NET validators and discusses a few case studies which may be a boon for any project
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CaseStudy1.aspx.cs" Inherits="CaseStudy1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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>
        <script type="text/javascript" language="javascript">
    var curobjid;
    var i=0;
    var isValid = true;
    
    //This function is going to be caled on the onfocus event of the textbox
    function AttachValidator(curObj, validatorClientID)
    {
        // isValid Check:If user enters some wrong value, then he will not ne allowed to some value in another textbox till he enters right value.
        if(isValid)
        {
            var validationControl = document.getElementById(validatorClientID);
            //Assigning controltovalidate properly to specific textbox dynamicaaly
            validationControl.controltovalidate = curObj.id;
            //Here also I am assigning the clientvalidationfunction.we can also change it dynamically based on the requirement. 
            validationControl.clientvalidationfunction="validatetextbox";
            validationControl.validateemptytext = "true"; 
            //This is the main function that is responsible for attaching th validator to the correspondng textbox 
            ValidatorHookupControl(curObj, validationControl);
            //keeping the textbox id in a global varable that is going to be used to show the callout
            curobjid=curObj.id;
        }
        else
        {
            document.getElementById(curobjid).focus();
        }
  
    }
    
    //This is Client validation function
    function validatetextbox(sender, args)
     {
        if(args.Value=="")
        {
            sender.errormessage="<b>Required Field Missing</b><br />This is required." ;
            args.IsValid = isValid = false;         
        }
        else if(isNaN(args.Value))
        {
            sender.errormessage="<b>Invalid field</b><br />Only Numbers are alowed." ;   
            args.IsValid = isValid = false;
          
        }
        else if(Number(args.Value)< 1000)
        {
            sender.errormessage="<b>Value can not be less than 1000</b><br />This is required." ;  
            args.IsValid = isValid = false;      
        }
        else
        {
            isValid = true;
        }
         if(!args.IsValid)
            ShowValidationCallout(sender, curobjid);
     }
 
 //This function is going update the postion of the callout so it gets visible at the proper place.    
function ShowValidationCallout(validationControl, elementClientID)
    {
        if(validationControl.ValidatorCalloutBehavior != null)
        {
            if(validationControl.ValidatorCalloutBehavior._popupBehavior != null)
            {
                validationControl.ValidatorCalloutBehavior._popupBehavior.set_parentElementID(elementClientID)
            }
            if(validationControl.ValidatorCalloutBehavior._errorMessageCell !=null)
            {
                validationControl.ValidatorCalloutBehavior._errorMessageCell.innerHTML = validationControl.errormessage;
                validationControl.ValidatorCalloutBehavior.show(true);
            }
                            
        }
    }
   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    <table border="1px" width="50%" style="font-family:Verdana">
        <tr>
            <td width="50%" style="font-weight:bolder">
                Name
            </td>
            <td width="50%" style="font-weight:bolder">
                Cost
            </td>
        </tr>   
        <asp:Repeater ID="rpUpdateAdpdetails" runat="server" OnItemDataBound="rpUpdateAdpdetails_ItemDataBound">
            <ItemTemplate>
                <tr style="border-top: 1px solid #E8E8E8">
                    <td style="border-top: 1px solid #E8E8E8">
                        <asp:Label ID="lblName" runat="server" Text="Label"></asp:Label>
                    </td>
                    <td style="border-top: 1px solid #E8E8E8">
                        <!--This is the textbox on the grid validator will be attached -->
                        $<asp:TextBox ID="txtCost" runat="server" Width="50px"></asp:TextBox>
                    </td>
                </tr>
            </ItemTemplate>
        </asp:Repeater>
     </table>
     <!-- This custom validator is going to attached dynamically on all the texboxes-->
        <asp:CustomValidator ID="gridValidator" runat="server" ></asp:CustomValidator>
           <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server" TargetControlID="gridValidator">
           </cc1:ValidatorCalloutExtender>
        
        <%--<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator
            ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
          <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender2" runat="server" TargetControlID="RequiredFieldValidator1">
    </cc1:ValidatorCalloutExtender>  
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ControlToValidate="TextBox1" ClientValidationFunction="validatetextbox"></asp:CustomValidator>
         <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender3" runat="server" TargetControlID="CustomValidator1">
    </cc1:ValidatorCalloutExtender> 
        <asp:Button ID="Button1" runat="server" Text="Button" />--%>
    </div>
    </form>
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions