Reputation: 1637
Right now when I submit the contact form with an input value other than 4, a successful message "Thanks, I'll get back to you soon!" returns and then the form is cleared. What should I change so that if I do enter an input value other than 4, the form is prevented from sending and user is alerted that the form failed?
I'm using this plugin for my contact form: http://malsup.github.com/jquery.form.js
// Contact form
(function(){
var contactForm = $('form#contact'),
inputCheck = $('input.check'),
contactCheck = $('div#contact-check');
// Check if answered math question correctly
inputCheck.keyup(function(){
if($(this).val() == 4){
contactCheck.fadeOut();
} else {
contactCheck.fadeIn();
}
});
// Validate input from contact form
$('form#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
clearForm: true,
success: function(){
// if it's good, do this
contactCheck.fadeOut();
alert("Thanks, I'll get back to you soon!");
}
});
return false;
},
invalidHandler: function(form) {
// if it's bad, do this
alert('Oops, something went wrong.');
}
});
})();
Upvotes: 0
Views: 40
Reputation: 388326
Add a custom validation rule like
jQuery.validator.addMethod("value", function (value, element, params) {
return this.optional(element) || params == value;
}, "Please specify the correct value");
then add a rule for the required element
// Validate input from contact form
$('#contact').validate({
rules: {
check: {
required: true,
value: 4
}
},
messages: {
check: {
value: 'The value must be 4'
}
},
submitHandler: function (form) {
$(form).ajaxSubmit({
clearForm: true,
success: function () {
// if it's good, do this
contactCheck.fadeOut();
alert("Thanks, I'll get back to you soon!");
}
});
return false;
},
invalidHandler: function (form) {
// if it's bad, do this
alert('Oops, something went wrong.');
}
});
Demo: Fiddle
Upvotes: 1