views:

289

answers:

3

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

+1  A: 

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.

Eoin Campbell
... which will require a noticeable postback unless Ajax-ified!
Cerebrus
Thanks for your answer but actually I want this to work client side too, seems like custom validators are the only way
Waleed Eissa
You can enable/disable Validator controls with client side javascript as well... http://msdn.microsoft.com/en-us/library/aa479045.aspx#aspplusvalid_clientside - search that page for the `ValidatorEnable` function
Eoin Campbell
Thanks, I'll check that
Waleed Eissa
+2  A: 

ASP.NET Validators offer a client-side API that allows you to :

  • validate client side
  • Hook up validators client side.
  • Enable or disable client side validators.

The syntax of the ValidatorEnable function is :

 ValidatorEnable(rfvMyValidator, boolState);
Cerebrus
Thanks a lot, I'm going to try that
Waleed Eissa
+1  A: 

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\"");
        }
Marwan Aouida
Thanks for taking the time to answer my question, as I mentioned in the question I have 3 radio buttons, with three sections (one section related to each radio button), each section contains one control that I need to validate, precisely in the first section I have a textbox, a fileupload in the second and dropdownlist in the third. I display a requiredfieldvalidator next to each control. The problem as you can see is that I have multiple RequiredFieldValidators. I'm going to try ValidatorEnable as mentioned in one of the answers.
Waleed Eissa