This question most closely relates to the asp.net mvc3 framework. It started out as “How can I ensure active validation for dynamically appended input fields using jQuery with asp.net mvc3?” However, after some searching, testing, and coffee I came across this:
function reValidate(formId) {
$("#" + formId).removeData("validator");
$("#" + formId).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#" + formId);
}
This works just fine. However, I am more curious about the mechanism that the framework is actually using. I have a page which is entirely generated based on a script. The only thing in the view is a <div>, a <script> tag to load my library, and another <script> to populate the <div>. After rendering an entirely dynamic page, the validation is flawless. However, if the same process which was used when the page loads is used after the page was loaded to include some new content then the validation breaks. Sure, just call reValidate().
But –
a) How does the framework instantiate the validation once the page has loaded (or as it loads)?
b) Which part of the framework handles it? Is it the mvc3 part, the asp.net part, the razor engine, or another part?
It parses the DOM, looks for
data-*attributes on your input fields and adds the jquery.validate rules. jQuery validate is a client side validation plugin which has nothing to do with ASP.NET MVC and could be used with any server side framework or even with plain static HTML.It’s the
jquery.validate.unobtrusive.jsscript. The ASP.NET MVC helpers such asHtml.TextBoxForsimply use the model metadata to generate input fields with the properdata-*attributes based on data annotations you used for your model. Those attributes contain all the necessary information in order to generate the native jquery validate rules. So the unobtrusive script makes the glue between the ASP.NET MVC Model metadata and thejquery.validateplugin. It’s the$.validator.unobtrusive.parsefunction that does this job. That’s the reason why you need to manually invoke it when you modify dynamically the DOM – you are adding/removingdata-*attributes that need to be translated into jquery validate rules. Don’t hesitate to look at how it is implemented insidejquery.validate.unobtrusive.js.