Reputation: 2609
I have the following JavaScript function:
$('div.nextStepBilling').click(function (e) {
if ($(this).parent().parent().attr("id") == "newCardDiv") {
$('form#myForm').validate({
rules: {
cardHolder: "required",
cardNumber: {
required: true,
minlength: 15,
maxlength: 16
},
CVV: {
required: true,
minlength: 3,
maxlength: 4
}
},
messages: {
cardHolder: "Card holder name is required",
cardNumber: {
required: "Credit card number is required",
minlength: "Credit card must be at least 15 digits long",
maxlength: "Credit card must be at most 16 digits long"
},
CVV: {
required: "CVV (security code) is required",
minlength: "CVV must be at least 3 digits long",
maxlength: "CVV must be at most 4 digits long"
}
}
});
if ($('form#myForm').valid()) {
alert("valid");
} else {
alert("invalid");
}
}
});
When I click on the proper div.nextStepBilling
it always alerts valid, even if there is nothing in those inputs.
I don't get any errors in the console and I can get jquery validate to work using $('form#myForm').validate().element("#cardHolder");
I have the latest jquery and jquery validate packages included (in proper order) on the page. Can anyone see anything wrong with the above code?
Upvotes: 1
Views: 643
Reputation: 98718
Your problem is here:
$('div.nextStepBilling').click(function (e) {
if ($(this).parent().parent().attr("id") == "newCardDiv") {
$('form#myForm').validate({
// rules & options
...
Because .validate()
is only the initialization method of the plugin, it is not the testing method. The .validate()
method only gets called once on DOM ready to initialize the plugin with your rules & options. All subsequent calls are ignored.
You would use the .valid()
method to programmatically trigger a validation test on demand.
Your code should look more like this...
$(document).ready(function() {
$('form#myForm').validate({ // initialize the plugin
// rules & options
});
$('div.nextStepBilling').click(function (e) {
if ($(this).parent().parent().attr("id") == "newCardDiv") {
$('form#myForm').valid(); // triggers a test on the form
...
Simple DEMOS: http://jsfiddle.net/zSq94/ and http://jsfiddle.net/zSq94/1/
Upvotes: 2