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
611 views
in Technique[技术] by (71.8m points)

javascript - MVC3 unobtrusive validation: how to remove/re-attach validation from a group of elements?

Here's the use case:

I have this long form with group of field that only becomes visible if the user makes a certain selection in one of the visible inputs. Reading Brad Wilson's post on the subject I thought jQuery.validator.unobtrusive.parse('.extra-data') where .extra-data is a class of a hidden div. No luck as the data was already there when the first parse was done.

So at the end I came up with this to remove the rules:

$('.data-panel').find('input[type="text"], textarea, select').each(function (i, item) {
    var currentRules = $(item).rules('remove'); // Saving removed rules to a sorta dictionary
    if (!$.isEmptyObject(currentRules)) {
        removedRules[$(item).attr("name")] = currentRules;
    }
 });

and this to re-attach them:

$('.data-panel').find('input[type="text"], textarea, select').each(function (i, item) {
    if (!$.isEmptyObject(removedRules[$(item).attr('name')])) {
        $(item).rules('add', removedRules[$(item).attr('name')]);
    }
});

Problem is, it feels kinda hacky as I'm literally going through each field removing and re-attaching those validation rules. My question is: isn't there a more straightforward way? Performance is also an issue, in one of those huge forms you can feel the delay between the click and the validation run.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Do not remove and re-attach rules. Just disable or enable inputs. Disabled fields do not participate in validation, neither do they get submitted to server.

//disable inputs. No validation will occur on these
$('.data-panel').find('input[type="text"], textarea, select').attr('disabled', 'disabled');

//enable inputs. Validation is re-enabled
$('.data-panel').find('input[type="text"], textarea, select').removeAttr('disabled');

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

...