Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/disable RequiredValidator on client-side / CustomValidator not firing

I've got a drop-down where the user selects a Country. It is a required "field".

Next to it, there is a textfield named State. If the user selects US, then the field State is required. If the user selects e.g. Sweden, the State is not required, since Sweden has no states.

Example code:

<asp:DropDownList runat="server" ID="Country"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="Country"
                runat="server" Display="Static" ErrorMessage="Required field" />

<asp:TextBox runat="server" ID="State"></asp:TextBox>
<asp:CustomValidator ClientValidationFunction="DoesntGetFiredIfStateIsEmpty"
                runat="server" Display="Static" ErrorMessage="Required field" />

<!-- SO, RATHER THIS TOGETHER WITH CONDITIONAL FIRING -->
<asp:RequiredFieldValidator ControlToValidate="State"
                runat="server" Display="Static" ErrorMessage="Required field" />

My question to you is: How can I make this CustomValidator fire validation when it is empty?

Or put simplier: How can I make a RequiredValidator fire conditionally?

Or simplest: How can I enable/disable a RequiredValidator on client-side?

like image 207
Simeon Avatar asked Apr 23 '10 14:04

Simeon


2 Answers

Try doing this with javascript to enable and disable validators

ValidatorEnable(RequiredFieldValidatorId, false);

Check out this question that I answered.

like image 64
hunter Avatar answered Sep 24 '22 08:09

hunter


Asp.net has a client side javascript function to manage the validators, the "ValidatorEnable" function,

ValidatorEnable(RequiredFieldValidatorId, false);

you can call it simply using javascript, you must send the validator object to the function (not only its id).

if (x==y) {
        ValidatorEnable($('#<%=rfvFamily.ClientID %>'), false);    
    } else {
        ValidatorEnable($('#<%=rfvFamily.ClientID %>'), true);
    }

or

if (x==y) {
        ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", false);    
    } else {
        ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", true);
    }

full documnet on: http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside

another way is to Set in your DropDownList CausesValidation="false" to avoid that the validators block a postback when you change the DropDownList entry.

(*) Remember this function is for client side, for disabling validator in server side, you must to disable validator on page postback too.

if (IsPostBack){
    if (x==y) {
        rfvFamily.Enabled = false;
    }
}
like image 34
Zakaria Habibi Avatar answered Sep 23 '22 08:09

Zakaria Habibi