I am popping up a JQuery dialog which has a form inside.
<div class="addcalevent">
<form name="caleventform" id="caleventform" method="get" action="" accept-charset="utf-8">
<div>
<label>Title</label>
<input type="text" id="txtcaltitle" name="title" />
</div>
<button id="savecalevent" >save</button>
</form>
</div>
When i popup the dialog, i am initializing the Jquery validation plugin.
$(".addcalevent").dialog(
{
height: 300,
width: 546
}
);
$('#caleventform').validate({
rules: {
title: {
required: true,
}
},
messages: {
title: {
required: "pls enter user name"
}
}
});
Ob button click .valid() always returns true.
$('.addcalevent').on('click', "#savecalevent", function (event) {
if (!$('#caleventform').valid()) {
return;
}
});
What am i doing wrong ? I am using Jquery version 1.10.2 and Validate version 1.11.0, Does the validation works only with a "Submit" button ?
Thanks !
I put your code into a jsFiddle and it clearly shows that .valid() working properly. It returns false when there are errors and true when the form is valid.
DEMO: http://jsfiddle.net/g65g6/
However, you should use the submitHandler callback function whenever you want to do something after clicking the button of a valid form. Use the invalidHandler callback to do something when the form is not valid. Use the .valid() method within a click handler for special cases where the button is not recognized as a submit button, or for programatically triggering/checking validity.
$(document).ready(function () {
$(".addcalevent").dialog({
height: 300,
width: 546
});
$('#caleventform').validate({
rules: {
title: {
required: true,
}
},
messages: {
title: {
required: "pls enter user name"
}
},
submitHandler: function(form) { // optional callback
// fires on button click when form is valid
// do any ajax here
return false;
},
invalidHandler: function() { // optional callback
// fires on button click when form is not valid
}
});
});
DEMO: http://jsfiddle.net/g65g6/1/
Documentation for all callback functions and options.
If you want to do things when the form is valid, use the submitHandler option of Validate.
$("#caleventform").validate({
rules: {
title: {
required: true
}
},
submitHandler: function () {
console.log('successful submit');
$('.addcalevent').dialog('close');
return false;
}
});
See it working here: http://jsfiddle.net/ryleyb/N5kjc/
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