Reputation: 3202
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.
Upvotes: 26
Views: 58902
Reputation: 18008
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.
Upvotes: 40
Reputation: 3202
I solved this easily by adding the following javascript on Client side.
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true); or
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);
Upvotes: 13
Reputation: 1588
You can enabled/Disabled the RequiredFieldValidator from the Javascript/jQuery. For your condition, When Checkbox is checked :- Just call the javascript function to enabled the RequiredFieldValidator and when its Uncheck just disabled the RequiredFieldValidator.
For other Conditions like Dropdown index change, textbox value change and radio button selection change you can call its onchange, onblur, onclick respectively and After executing the required condition you can Enabled/Disabled the RequiredFieldValidator.
Hope this help you.
Upvotes: 0
Reputation: 1526
Try this...
protected void RequiredFieldValidator1_Load(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
RequiredFieldValidator1.Enabled = true;
}
else if (CheckBox1.Checked == false)
{
RequiredFieldValidator1.Enabled = false;
}
}
Upvotes: 1
Reputation: 17366
You can also try this one
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
if(CheckBox.Checked)
{
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ValidationGroup = "anything";
Button1.ValidationGroup = "anything";// your save button
}
else
{
RequiredFieldValidator1.Enabled = false;
RequiredFieldValidator1.ValidationGroup = string.Empty;
Button1.ValidationGroup = string.Empty; // save button
}
}
Upvotes: 1