Reputation: 1471
I am using jquery validate http://jqueryvalidation.org/
I have a form with a first field added manually (hard coded)
Then adding more fields is done programatically. The ARE appended inside the form tags already, into a div #to-append
The one added manually validates fine.
For the rest, I am trying to add the rules like this, every time i add a field:
var $largestID = $("#to-append > div:last > div:first > input:first").attr("id");
console.log($largestID); //throws right id
$($largestID).rules("add", {
required: true,
minlength: 3,
pattern: yt
});
But get the "Uncaught TypeError Cannot read property 'form' of undefined" error stated above.
Any help would be appreciated.
Upvotes: 1
Views: 37959
Reputation: 18657
You are adding rule taking ID string. Instead take the element selector, and add rule to that selector.
var $largestID = $("#to-append > div:last > div:first > input:first").attr("id");
console.log($largestID); //throws right id
$('#'+$largestID).each(function () {
$(this).rules('add', {
required: true,
minlength: 3,
pattern: yt
});
});
Use the $('#'+$largestID)
to get the field of that ID, and then add rules.
To add rules to array, use:
$('#'+$largestID).each(function () { })
you can even validate the array of names of that element:
$('#'+$largestID).validate({
rules: {
'url[]': {
required: true,
}
}
});
Upvotes: 4
Reputation: 782683
There's no need to use the ID. You have a selector that returns the element, add the rule to that directly.
$("#to-append > div:last > div:first > input:first").rules("add", {
required: true,
minlength: 3,
pattern: yt
});
Upvotes: 1