I've got some dynamically inserted form fields on a page in an MVC3 project. Normally we would add the jQuery validation server-side, but in this case we can't (multiple fields in the UI generate the value for one hidden field - and this is what is submitted. We can't validate against a hidden field, so we must instead add UI-only validation for the fields the user can see)
Once the fields are dynamically added to the page, I run the following code over the container:
$container.find(".date").rules("add", {
required: true,
messages: {
required: "The date is required"
}
});
But it doesn't work! Oddly enough, disabling the above code, creating the dynamic elements, then running the code in the browser JS console works, but only the default validation message shows.
I'm at a loss. Any ideas?
I am using jQuery Validation 1.9.0 & the unobtrusive plugin
jQuery is a Javascript library. An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side.
The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.
rules: { username: { minlength: 6, maxlength: 12, remote: { url: 'register/isUsernameAvailable', dataType: 'post', data: { 'username': $('#username'). val() }, success: function(data) { if (data. username == 'found') { message: { username: 'The username is already in use!
As it turns out, this can be done mostly in HTML by adding a few attributes to each form element:
name
attributedata-val="true"
data-val-required="message"
Like so:
<input type='text' name="date" data-val="true" data-val-required="A date is required." />
Then the form just needs to be re-parsed via JS:
//Remove current form validation information
$("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
//Parse the form again
$.validator
.unobtrusive
.parse("form");
I think you had something more simple wrong - like your find('.date')
wasn't actually finding anything. Because otherwise, your code looks quite reasonable to me. Here is an example of it working as you expected: http://jsfiddle.net/ryleyb/LNjtd/
I was able to validate the code correctly with this:
$('form fieldset')
.append('<br>New Field: <input type="text" name="newField"> * Also required')
.find('input[name="newField"]').rules('add', {
required: true,
messages: {
required: 'New field is required'
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With