Reputation: 301
I'm using the jquery validate plugin, and I want to place errors next to the invalid form element. However, I ALSO want to have all the errors listed at the top of the form.
The options settings seem only to let you do one or the other, but not both.
So if there is a way to set the options so that this happened, that would solve the problem easily!
To try and get around this, I wrote a snippet of jQuery to take the error messages and add them to the top of the form (and link them to the error location). However, when I try to call this function within the validate method (either using the invalidHandler or errorPlacement handlers), everything works alright, BUT the form gets submitted. I don't want the form submitted, as the jQuery is there to validate client-side.
My validate options look like this:
$("#memberRegistration").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.errorBox span").html(message);
}
$("div.errorBox").removeClass('noDisplay');
errorCopy(); // <-- my custom function
},
wrapper: "div",
errorPlacement: function(error, element) {
element = element.closest('li');
element = element.children(':first-child');
error.insertBefore(element);
error.addClass('message');
},
meta: "validate",
rules: {
"memberRegistrationFormDetails.Title": { required: true },
Why can't I call a function from the invalidHandler or errorPlacement handlers without the form being submitted?
Thanks!
Upvotes: 2
Views: 3829
Reputation: 301
Found a solution. I added the relevant code straight to the errorPlacement handler without calling the function from elsewhere, and with some modifications:
errorPlacement: function(error, element) {
element = element.closest('li');
element = element.children(':first-child');
error.insertBefore(element);
error.addClass('message');
$(function() { // my function
var errorIndex = $(error).index('div');
var errorId = 'errordiv' + errorIndex.toString();
$(error).attr('id', errorId);
$('.errorList').append('<li><a href="#' + errorId + '">' + $(error).text() + '</a></li>');
});
},
This code takes the error message and adds a link to it into my errorList container at the top of the form.
Upvotes: 2