Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp:RequiredFieldValidator validation based on conditions

Tags:

I have validation as below but only like to triggered if the checkbox is ticked.

<!-- TextBox and its validator --> Name: <asp:TextBox ID="TextBox1" runat="server" />  <asp:RequiredFieldValidator runat="server"         ID="RequiredFieldValidator1"          Text="*"         ErrorMessage="Name is required"          ControlToValidate="TextBox1" /> 

Can I get it done using asp:RequiredFieldValidator?
I only like to validate if a certain condition matched.
Currently it is validating every time the 'Save' button is clicked.

like image 722
ove Avatar asked May 28 '13 11:05

ove


1 Answers

Use a custom validator instead:

<asp:CustomValidator ID="cv1" runat="server"         ErrorMessage="Name is required"         Text="*"         ControlToValidate="TextBox1"         ValidateEmptyText="True"          ClientValidationFunction="validate" /> 

and the script (just checking a checkbox and the textbox value as example; you can use custom logic):

<script type="text/javascript">     function validate(s,args){         if(document.getElementById("<%= checkboxId.ClientID %>").checked){             args.IsValid = args.Value != '';          }         else{             args.IsValid = true;         }     } </script> 

This will do the client-side validation. If you need server validation also, add the OnServerValidate attribute, and a handler on code behind. See here for details.

like image 74
mshsayem Avatar answered Sep 21 '22 19:09

mshsayem