I am working with ASP.Net MVC3
, the easier way to use the client validation would be enabling the jquery.validate.unobtrusive
. Everything works fine, for stuff that's right from server.
But when I try to inject some new 'inputs' with javascript, and I knew that I need to call $.validator.unobtrusive.parse()
to rebind the validations. But still, all those dynamic injected fields are not functioning.
Even worse, I try to manually bind using jquery.validate
and it is not working either. Any thoughts?
Why not use the rules function directly from jquery validation doc. Like this:
I tried viggity's answer and at first everything seemed to work. But after a while i noticed that the validation becomes painfully slow the more dynamically items I added. The reason was that his solution doesn't unbind the event handlers, but add new ones each time. So if you add 5 items the validation is executed 6 times instead of only once. To fix this you have to unbind the events additionally to the removeData calls.
I have been fiddling around with this for a while, scrapping solutions and trying again later (when I had some spare time, believe it or not).
I am not sure if this behaviour would have changed in newer versions of jquery (we're using 1.7.2) since this thread was created or commented last, but I found that
.parseElement(inputElement)
works fine when I try to add dynamically created elements to a form that already has a validator loaded. This was already suggested by @jamesfm (Feb 15 '11) in one of the comments above, but I overlooked it the first few times I was working on this. So I'm adding it as a separate answer to make it more obvious and because I think it is a good solution and doesn't require so much overhead. It might not be relevant for all the issues raised in subsequent answers but I think it would be a solution to the original question. Here's how I got mine working:I am using MVC 4 and JQuery 1.8, looks like the following piece of code is needed to enable Jquery to validation dynamically injected content via Ajax, or Jquery into the DOM.
I have made a modular function which accepts the Jquery object of the newly added element. If you have cloned a new table with id
tblContacts
using Jquery on click of a button, then include the function below in your js fileand call it like this:
I've created an extension for the jquery.validate.unobtrusive library that solved this problem for my situation - it might be of interest.
http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
I actually really like the simplicity of @viggity and @Robins solution, so I turned it into a quick little plugin:
Example usage: