MVC3 unobtrusive validation: how to remove / reattach validation from a group of elements?

A use case is used here:

I have this long form with a group of fields, which becomes visible only if the user makes a specific choice in one of the visible inputs. Reading Brad Wilson's post on the topic I thought jQuery.validator.unobtrusive.parse ('. Extra-data'), where .extra-data is the class of the hidden div. No luck, because the data was already there when the first parsing was done.

So in 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 for their reattachment:

 $('.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')]); } }); 

The problem is that it looks a bit hacky, as I literally look at each field, deleting and re-securing these validation rules. My question is: is there an easier way? Performance is also a problem, in one of these huge forms you can feel the delay between clicks and the validation run.

+6
source share
1 answer

Do not delete and reattach rules. Just disable or enable inputs. Disabled fields do not participate in the validation, and they are not sent to the 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'); 
+23
source

Source: https://habr.com/ru/post/898759/


All Articles