Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

asp.net - Dynamically enable or disable RequiredFieldValidator based on value of DropDownList

I have an ASP.NET form with three text inputs, one each for "Work Phone", "Home Phone" and "Cell Phone". Each of these text inputs has a RequiredFieldValidator associated with it. I also have a DropDownList where the user can select the preferred phone type.

I want to only require the field that is selected in the DropDownList. For example, if the user selects "Work Phone" from the DropDownList, I want to disable the RequiredFieldValidator for "Home Phone" and "Cell Phone", thereby only making the "Work Phone" field required.

I have a method that enables and disables these validators based on the value of the DropDownList, but I cannot figure out when to call it. I want this method to run before the validation takes place on the page. How would I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...