Reputation: 83
I've looked around on Stack to try and find a solution to a problem that I've encountered with my jQuery validation. I've decided to change my error messages, that were below my input fields to a single generic all encompassing message placed above the form. I have a class "hide" on that message "#error_mail" that I want to replace with "error" when there is an error in the field(s) on submission/validation. Any help would be greatly appreciated, thanks in advance.
HTML
<form action="#" method="post" class="new_web_user" id="new_web_user" autocomplete="off">
<p class="fields-required">
*Required fields</p>
<p id="error_mail" class="hide">We're sorry, the fields highlighted in red are required</p>
<div class="field-column"> etc etc.....
JS
$(function(){jQuery.validator.setDefaults({
errorContainer: "#error_mail",
errorPlacement: function(error, element) {
error.appendTo('#error_mail');
},
ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input'
});
$('#new_web_user').validate({
rules: {
web_user_title: {required: true},
web_user_given_name: {
required: true
},
web_user_family_name: {
required: true
},
web_user_email: {
required: true,
email: true
},
email_confirmation: {
required: true,
equalTo: '#web_user_email'
},
web_user_country: {
required: false,
},
},
messages : {
web_user_title: {
required: "Please select a title."
},
web_user_given_name: {
required: "Firstname is required."
},
web_user_family_name: {
required: "Lastname is required."
},
web_user_email: {
required: "Email address is required.",
email: "Email address seems invalid."
},
email_confirmation: {
required: "Email address is required.",
equalTo: "Email addresses do not match."
},
web_user_country: {
required: "Please choose your country."
}
},
submitHandler: function(form) {
$.ajax({
Upvotes: 0
Views: 1483
Reputation: 21226
You can simplify this a lot, using the options available in jQuery Validate:
$("#new_web_user").validate({
errorContainer: '#error_mail',
errorLabelContainer: '#actual_errors',
wrapper:'li',
//your rules and messages here
});
Then, change your HTML to be something more like this:
<p id="error_mail" class="hide error">
We're sorry, the fields highlighted in red are required
<ul id="actual_errors"></ul>
</p>
Note that instead of adding/removing the error class you want on #error_mail
, just set it at all times, as it will only be visible when there is a problem...
See it working here: http://jsfiddle.net/cayjuwf4/
Upvotes: 1