DCR DCR - 7 months ago 48
Javascript Question

Jquery error placement with required from group

I'm using the following js and trying to integrate it with error placement. Basically I'm trying to print the error message just for the required from group to a specific div.

I think I should use something like:

errorPlacement: function(error, element) {
if (element.attr("class") == "days_group" )
error.insertAfter("#special_place");
else
error.insertAfter(element);
}


but I'm not sure if that will work or where to place the code in what follows:

Here's a link to jsfiddle (you need to get to the third page)

$(".next").click(function(){
var form = $("#reg_form");
form.validate({
errorElement: 'span',
errorClass: 'help-block',
highlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').addClass("has-error");
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass("has-error");
},

groups: {
days_groups: "M Tu W Th F Sa Su"
},



rules: {
M:{
require_from_group:[1,'.days_group']
},
Tu:{
require_from_group:[1,'.days_group']
},
W:{
require_from_group:[1,'.days_group']
},
Th:{
require_from_group:[1,'.days_group']
},
F:{
require_from_group:[1,'.days_group']
},
Sa:{
require_from_group:[1,'.days_group']
},
Su:{
require_from_group:[1,'.days_group']
},
first_name: {
required: true,
},
last_name: {
required: true,
},
email1 : {
required: true,
},
email2 : {
required: true,
equalTo: '#email1',
},
pass1 : {
required: true,
},
pass2 : {
required: true,
equalTo: '#pass1',
},
day: {
require_from_group: [1, ".days-group"]
},




},
messages: {
M: {
require_from_group: "Please select at least 1 day"
},
Tu: {
require_from_group: "Please select at least 1 day"
},
W: {
require_from_group: "Please select at least 1 day"
},
Th: {
require_from_group: "Please select at least 1 day"
},
F: {
require_from_group: "Please select at least 1 day"
},
Sa: {
require_from_group: "Please select at least 1 day"
},
Su: {
require_from_group: "Please select at least 1 day"
},
first_name: {
required: "First name required",
},
last_name: {
required: "Last name required",
},
email1: {
required: "Email required",
},
email2: {
required: "Confirm Email required",
equalTo: "Emails do not match",
},
pass1: {
required: "Password required",
},
pass2: {
required: "Confirm password required",
equalTo: "Passwords do not match",
},






}



});

Answer

Try this:

errorPlacement: function(error, element) {
    if (element.hasClass("days_group")) {
        error.insertAfter("#special_place");
    } else {
        error.insertAfter(element);
    }
}

Proof of Concept: http://jsfiddle.net/dsj4zg21/

Comments