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

a 夏天 提交于 2019-12-22 05:06:32

问题


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?


回答1:


Try doing this with javascript to enable and disable validators

ValidatorEnable(RequiredFieldValidatorId, false);

Check out this question that I answered.




回答2:


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


来源:https://stackoverflow.com/questions/2699445/enable-disable-requiredvalidator-on-client-side-customvalidator-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!