简体   繁体   中英

Jquery client side validate not working

I am trying to using a jquery.validate.unotrusive.js plugin to dynamically created form fields like:

var message = $("<textarea id='test'></textarea>");
$(message).attr("data-val", "true")
.attr("data-val-number", "The field CustomerId must be a number.")
.attr("data-val-required", "The CustomerId field is required.");

var span = $('<span class="field-validation-valid" data-valmsg-replace="true"></span>');
$(span).attr("data-valmsg-for", $(message).attr("id"));

var form = $("<form action='url'></form>");

$(form).append(message,span);

I embed both jquery.validate & jquery.validate.unobtrusive js files but textarea field is not validate on form submission. Can anybody tell whats going wrong here?

When you add new elements to the DOM dynamically you will need to reparse the unobtrusive validation rules in order to register them. So once you have appended the form to the DOM invoke the $.validator.unobtrusive.parse method to inform the client validation framework of those changes:

...
$(form).append(message, span);
$.validator.unobtrusive.parse(form);

And if you are only dynamically adding input elements to an already existing form in the DOM for which the client side validation has been registered you will also need to remove previous rules for this form:

// adding some form elements to an existing form ...

$(form).removeData('validator').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM