I am using jQuery's unobtrusive validation plugin in with ASP.NET MVC. Any fields that are rendered on the server are properly validated.
However, if I dynamically add a field in the form using JavaScript, it is not validated even though it has the appropriate HTML5 data-*
attributes.
Can anyone guide me in right direction on how I can achieve this goal?
Here's a blog post you may find useful and that should put you on the right track. Extension method taken from there:
and then:
Updated to add fix referenced in blog post comments, otherwise js errors occur.
Simpler Answer:
I am using MVC 4 and JQuery 1.8. I have made it to a modular function which accepts the jQuery object of the newly added element:
For example, if you added a new table with id
tblContacts
, then you can invoke like this:In order for Darin's answer to work, I changed the following line:
To this:
Here's the full sample:
$.validator.unobtrusive.parse
internally calls parseElement method but each time it sendsisSkip
parameter to true so with this valuethis code in jquery.unobtrusive.js does not attach validation to the element and we find only validation data of inputs that were initially present on the page.
Note Darin's answer above is correct and you can find on the blog he referred that many people have solved problem using xhalent's code (posted by darin). why it did not work is beyond my understanding. Moreover, you can find plenty of posts that tell you that just calling
is enough for dynamically loaded content to be validated