Labels

Tuesday, May 22, 2007

Custom Validatorss

 

By simply using the four ASP.NET validation Web controls (the RequiredFieldValidator, the CompareValidator, the RangeValidator, and the

RegularExpressionValidator), we are able to solve the vast majority of our form validation needs. However, there may be times when we need

 to perform more complex , more conditional validation logic.In such cases CUSTOM VALIDATOR comes into picture.

 

Building a simple CustomValidator Control

 

The below code shows a simple Web form with a text box, a checkbox and a button. if the checkbox is checked , the textbox should not be

 empty and if it is unchecked the textbox can be empty. We are providing client side validation for this .

 

 

 <script type="text/javascript">

 

//function for checking the validation

 function CheckEmpty(sender, args)

   {

    var check=document.getElementById("CheckBox1");

 

         if(check.checked==true)

          {

              if(args.Value=="")

               {

                 args.IsValid =false;

               

               }

              else

                args.IsValid = true;

          }

    } 

    </script>

</head>

 

<body> 

    <form id="form1" runat="server">     

     

           <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

           <asp:CheckBox ID="CheckBox1" runat="server" />

           

          <%--  custom validator--%>

         <asp:CustomValidator runat="server" id="custPrimeCheck"  ControlToValidate="TextBox1"   ValidateEmptyText="true" 

                                 ClientValidationFunction="CheckEmpty"  ErrorMessage="Please enter some data" />

 

        <asp:button ID="Button1" runat="server" text="Button" />

      </form>

 

</body>

</html>

 

 

 

 

The args parameter passed in the CheckEmpty() function contains two properties that are vitally important:

 

Value - indicates the value of the form field the CustomValidator control is validating.

IsValid - a Boolean property , Set IsValid to true if the Value is valid, false otherwise.

 

We can also perform server side validation using Custom validators.

 

 

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

No comments:

Post a Comment