I want to use jQuery Validate to validate some form fields using a anchor onclick handler as follows but it doesn't seem to work?
<input type="text" id="StartDate" name="StartDate">
<input type="text" id="EndDate" name="EndDate">
<a class="btn btn-primary js-add" href="#">Add</a>
<script>
$(document).on('click', '.js-add', function (e) {
e.preventDefault();
var validator = $("form").validate({
rules: {
StartDate: {
required: true
},
EndDate: {
required: true
}
},
messages: {
StartDate: "The Start Date is required",
EndDate: "The End Date is required"
}
});
if (!validator.valid()) {
console.log("invalid");
return;
}
// otherwise do stuff but we dont want to submit form
});
</script>
I want to validate the fields and if they are valid do some other stuff inside the handler but I dont want to submit the form as I have another button for submitting the form. The validator.valid() function in the above is always true. When I submit the main button i dont need to validate the above fields as they are not mandatory - this is just for some client side interactivity that i need to validate the above fields.
is there any way I can achieve the above?
submitHandler: function(form) { /* do anything except form.submit();*/ }