I have a page with three radio buttons, depending on which button is selected I need to validate some controls (using required field validators). Other than using custom validators, is there any way to do this?
Thanks
I have a page with three radio buttons, depending on which button is selected I need to validate some controls (using required field validators). Other than using custom validators, is there any way to do this?
Thanks
ASP.NET Validators offer a client-side API that allows you to :
The syntax of the ValidatorEnable
function is :
ValidatorEnable(rfvMyValidator, boolState);
Add an OnSelectedIndexChanged to the RadioButtonList (or CheckedChanged if they're individual Radio button controls)
In the code behind, .Enable
& .Disable
the specific required field validators.
I tried this on a small example and it worked for me:
I have
-2textboxes: TextBox1 and TextBox2
-RequiredFieldValidator : RequiredFieldValidator1 with ControlToValidate="TextBox1"
-RadioButton : RequiredFieldValidator1
This code is generated by the RequiredFiledValidator:
<script type="text/javascript">
//<![CDATA[
var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");
RequiredFieldValidator1.controltovalidate = "TextBox1";
RequiredFieldValidator1.errormessage = "RequiredFieldValidator";
RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
RequiredFieldValidator1.initialvalue = "";
//]]>
</script>
I want when the user click on the RadioButton1 to switch the validation to TextBox2.
This is how I did it:
protected void Page_Load(object sender, EventArgs e)
{
RadioButton1.Attributes.Add("onclick", "RequiredFieldValidator1.controltovalidate=\"TextBox2\"");
}
Waleed, you do not specify whether you are using ASP.Net forms or ASP.Net MVC.
If you are using ASP.Net MVC, the answer is quite simple...
Firstly, you should create a ModelView class which should include the boolean attributes corresponding with your radiobuttons.
Just use the Foolproof validation library that is available on Codeplex and should work out-of-the-box for your problem: https://foolproof.codeplex.com/
It supports, amongst others, the following "requiredif" validation attributes / decorations:
[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
To get started is easy:
All that is then left to do, is to decorate your fields which should be conditionally validated with the [RequiredIfTrue]
attribute, which should point to the corresponding radiobutton value in your ViewModel.