I am using the JQuery Validate plugin to handle validation for my forms. I have a requirement to have the error at 2 places:
I have it working at the field level, but how do I get it to work for both the top and at the field level.
At the top of the form, I want to have something like this:
<p>You have the following error messages:</p>
<li>First Name - This is a required field</li>
<li>Last Name - This a required field</li>
<li>Email Address - This is a required field</li>
At the form level, i have error messages showing up such as this which is working:
First Name
This is a required field
[ ]
Last Name
This is a required field
[ ]
Email
This is a required field
[ ]
Here is the HTML Code
<html>
<body>
<div id="errormessages"></div>
<form id="myform">
<label for="firstname" class="required">First name</label> <input type="text" required="required" name="firstname" id="firstname" class="textInput" /></div>
<label for="lastname" class="required">Last name</label> <input type="text" required="required" name="lastname" id="lastname" class="textInput" /></div>
<label for="email" class="required">Email</label> <input type="text" required="required" name="email" id="email" class="textInput" /></div>
</form>
</body>
<html>
Jquery code for error messages placed at the form level:
$("#myform").validate({
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
email: {
required: true
}
},
errorPlacement: function(error, element) {
error.insertBefore(element);
}
});
so how would i build the code to have it at both locations?
Thanks Cheers
Quote OP:
"so how would i build the code to have it at both locations?"
See the showErrors
option as contained in the documentation.
This will give you a good start (needs some tweaking)...
$("#myform").validate({
// your rules here,
// call back for placement of messages within form
errorPlacement: function (error, element) {
error.insertBefore(element);
},
// callback for custom error display
showErrors: function (errorMap, errorList) {
// summary of number of errors on form
var msg = "Your form contains " + this.numberOfInvalids() + " errors, see details below.<br/>"
// loop through the errorMap to display the name of the field and the error
$.each(errorMap, function(key, value) {
msg += key + ": " + value + "<br/>";
});
// place error text inside box
$("#errormessages").html(msg);
// also show default labels from errorPlacement callback
this.defaultShowErrors();
// toggle the error summary box
if (this.numberOfInvalids() > 0) {
$("#errormessages").show();
} else {
$("#errormessages").hide();
}
} // end showErrors callback
});
Working DEMO: http://jsfiddle.net/M5pzA/
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