开发者

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?


Try doing this with javascript to enable and disable validators

ValidatorEnable(RequiredFieldValidatorId, false);

Check out this question that I answered.


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜