I'm using the jQuery validate plugin to validate a form. All fields are mandatory and space for error messages is limited on the form, so is it possible to show a single error message if any of the fields from my rules aren't completed which says, 'All fields must be completed before you submit the form' ?
My jQuery knowledge is limited and I can only figure from examples how to set it up so that it outputs individual error messages for each field using the following code:
$(".contact-form").validate({
errorLabelContainer: ".form-errors",
wrapper: "li",
ignore: ".ignore",
errorElement: "em",
rules: {
first_name: { required: true },
last_name: { required: true },
email: { required: true, email: true }
},
messages: {
first_name: "Please enter your first name",
last_name: "Please enter your last name",
email: { required: "Please enter your email address", email: "Your email address must be in the format of [email protected]" }
},
});
This will do what you have asked for:
Javascript
$(".contact-form").validate({
ignore: ".ignore",
rules: {
first_name: {
required: true
},
last_name: {
required: true
},
email: {
required: true,
email: true
}
},
showErrors: function(errorMap, errorList) {
$(".form-errors").html("All fields must be completed before you submit the form.");
}
});
Demo
Although this error message isn't very good for when someone enters an incorrect email address, as all fields have been filled in but there is still an error in the form.
Also, note you can specify required fields in the form by setting their class
attribute to required
:
HTML
<form class="contact-form" type="post" action="">
<input type="text" name="first_name" id="first_name" class="required" />
<input type="text" name="last_name" id="last_name" class="required" />
<input type="email" name="email" id="email" class="required email" />
<input type="submit" />
<div class="form-errors"></div>
</form>
Javascript
$(".contact-form").validate({
showErrors: function(errorMap, errorList) {
$(".form-errors").html("All fields must be completed before you submit the form.");
}
});
Demo
Looks like the invalidHandler is what you need. Take a look at this example (source: http://docs.jquery.com/Plugins/Validation/validate#toptions):
$(".selector").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
})
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