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?
Firstly, I think the call should be to .validator, not validate then you need to pass in the id of the form
Taking from Xhalent's solution marked as answer above, I expanded on it a bit.
So basically it still works the same as Xhalent's solution above but I added the ability to remove rules for elements you remove from the dom. So, when you remove elements from the Dom and you want those validation rules removed also then call:
I tried Xhalent's approach but unfortunately it wasn't working for me. Robin's approach did work and didn't work. It worked great for dynamically added elements, but if you tried to use JQuery to remove all the validation attributes and spans from the DOM, the validation library still would try to validate them.
However, if you remove the form's "unobtrusiveValidation" data in addition to "validationData", it worked like a charm for dynamically adding and removing elements that you want validated or not validated.
I'm having the same problem. I discovered it's not possible to call $.validator.unobtrusive.parse() on the same form twice. When loading the form initially from the server the form is parsed automatically by the unobtrusive library. When you add an input element dynamically to the form and call $.validator.unobtrusive.parse() again, it won't work. The same goes for parseElement().
The unobtrusive lib calls the validate method of the jquery validate plugin to set all the rules and messages. Problem is, when called again, the plugin doesn't update the new set of rules its given.
I found one crude solution: Before calling the parse method on the unobstrusive lib, i throw away the form validator:
Now, when the validate method is called by the unobtrusive lib, all rules and messages are recreated including the dynamically added inputs.
Hope this helps
In case of dynamic contents you need to update Unobtrusive Validations as below and check if
Form
is valid while submitting.I found @Xhalent's code script in my code and was going to delete it because I was not using it, which lead me to this SO question.
This code is pretty clean and simple:
Then, to call this jQuery extension, just use a selector to grab you form:
Viola!