Dynamically enable or disable RequiredFieldValidator based on value of DropDownList

坚强是说给别人听的谎言 提交于 2019-11-28 05:43:56

Why not use a CustomValidator in this case? Turning off/on a RequiredFieldValidator could lead to a design issue in the future - I'd stick to using them on fields that are going to be required.

You can do this with JavaScript like this:

ValidatorEnable(RequiredFieldValidatorId, false);

Then have your drop down list use the onchange event (I'd suggest using jQuery)

$("#<%=dropDownList.ClientID %>").change(function(){
    var val = $(this).val();
    var skip = null;
    if (val == 1)
       skip = "workPhoneValidator";
    else if (val == 2)
       skip = "cellPhoneValidator";
    ....

    // by popular demand...
    var $skip = $("#" + skip)[0];

    if (skip != "workPhoneValidator") ValidatorEnable($skip, false);
    if (skip != "cellPhoneValidator") ValidatorEnable($skip, false);
    ....
});
Gouse

When you are using home phone, in dropdown selectedindexchange event, make the required field validators invisible.

like..

if homephone is selected,

homephonevalidator.visible=true
cellphonevalidator.visible=false
workphonevalidator.visible=false

if cellphone is selected,

homephonevalidator.visible=false
cellphonevalidator.visible=true 
workphonevalidator.visible=false

if workphone is selected,

homephonevalidator.visible=false
cellphonevalidator.visible=false
workphonevalidator.visible=true

Possible way would be:

  • Set in your DropDownList AutoPostBack="true"
  • In the SelectedIndexChanged event handler of the DropDownList enable/disable your validators
  • Set in your DropDownList CausesValidation="false" to avoid that the validators block a postback when you change the DropDownList entry.

OnChange event of the drop down you may have something like this

function EnableValidator(){
    ValidatorEnable(requiredFieldValidator, validatorMustBeEnabled);
} 

Check on this url. Section "Client-Side APIs"

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

OnChange of the DropDownlist, you will need to register a server-side event handler that enables/disables the validator...

HTH

sam k

This is good way to enable and disable server side control validation from jquery event:

<label class="label_radio" for="Oversize"  onclick="EnableDisbledValidator('show')">show textbox</label>

<asp:TextBox ID="txtNote" runat="server" class="checkvalidation"></asp:TextBox>

 <asp:RequiredFieldValidator ID="rfvNote" runat="server" ControlToValidate="txtNote" SetFocusOnError="true" ErrorMessage="Please enter the note" Display="Dynamic" CssClass="error-tooltip"></asp:RequiredFieldValidator>

function EnableDisbledValidator(lblShow) {
    if (lblShow == "hide") {;
        ValidatorEnable($('#<%=rfvNote.ClientID %>')[0], false);

    } else {
        ValidatorEnable($('#<%=rfvNote.ClientID %>')[0], true);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!