BeanSoftware Logo
 

 
ASP.NET Database Search Control
 
 

 
 Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Can I Get Conditional RequiredFieldValidator On Client Side?

Let say you have one text box that requires validation only if some condition on client side is true. Good example could be a form for feedback that contains one CheckBox "Please Answer Me". If visitor wants to receive an answer from site admin, she must give an e-mail address in next TextBox control. In other case, if CheckBox control is not checked, she can send a feedback comment without giving an e-mail address.

It is pretty easy to implement required field validation for static case. Just use the RequiredFieldValidator and set its ControlToValidate property to ID of TextBox control. But, if validation depends of any client side condition, you need to use CustomValidator. You can do it with code like this:

<form id="form1" runat="server">
  <div>Your Comment:<br />
   <asp:TextBox ID="txtComment" runat="server" Columns="30" Rows="5"
    TextMode="MultiLine"></asp:TextBox>
   <br />
   <asp:CheckBox ID="chkPleaseAnswerMe" runat="server" Text="Please Answer Me" />
   <br />
   E-mail:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
   <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateCheckBox"
    ErrorMessage="If you require answer please write your e-mail address."></asp:CustomValidator>
   <br />
   <br />
   <asp:Button ID="btnSendComment" runat="server" Text="Send Comment" />
   <script language="javascript" type="text/javascript">
    function ValidateCheckBox(Source, args)
    {
     var chkAnswer = document.getElementById('<%= chkPleaseAnswerMe.ClientID %>');
     var txtEmail = document.getElementById('<%= txtEmail.ClientID %>');
 
     if(chkAnswer.checked != false){
      if(txtEmail.value == "")
       args.IsValid = false;
      else
       args.IsValid = true;
      }
    }
   </script>    
  </div>
 </form>

 

You can test this code, if you click "Send Comment" button while chkPleaseAnswerMe CheckBox control is not checked the form will submit, but if check box is checked and txtEmail is empty, TextBox txtEmail will not pass client side validation and you'll get a message that e-mail is in this case required.



Related articles:

1. Export Crystal Reports to PDF file

FAQ toolbar: Submit FAQ  |  Tell A Friend  |  Add to favorites  |  Feedback



Copyright © 2002-2008 Bean Software. All rights reserved.