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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With