How to make this custom validation rule in JQuery?

Hi there

I want to make some custom rule in jQuery(I have experience in making custom rule in jquery).

Suppose I have 3 checkbox checkbox1,checkbox2,checkbox3,What I want when user has not selected any one of those group values then a custom message will be displayed using JQuery or if this is possible in other third party library?.

So far I don’t have any code snipshot to it.If someone share some Idea how this can be acheived then I will try to write code.

Thanks

I used this plugin for a project recently and it was great. Specifically they have a “require” validate method which means that the form element needs to be filled out. I assume in checkboxes that means at least one filled out.

http://jqueryvalidation.org/

The documentation for the validator options seems to have everything that you might need.

I’ve put together three different examples below, that cater to different types of needs that you may have:

  • checkboxes all have the same name
  • checkboxes have different names with different rules and/or messages
  • checkboxes have different names with the same rules and messages

Checkboxes with the same name

For example, I’ve created a sample form:

<form id="checkboxTest">
    <p id="itemErrors"></p>
    <p><label><input type="checkbox" name="item[]" value="item 1"> Item #1</label></p>
    <p><label><input type="checkbox" name="item[]" value="item 2"> Item #2</label></p>
    <p><label><input type="checkbox" name="item[]" value="item 3"> Item #3</label></p>
    <p><input type="submit" name="submit" value="Submit">
</form>

That uses the following rules:

rules: {
    "item[]": {
        required: true,
        minlength: 2
    }
},

Which replaces the default messages with these custom ones:

messages: {
    "item[]": {
        required: "Please select at least one item.",
        minlength: "Please choose more than one"
    }
},

And tells the errors for those checkboxes to appear together in a custom location:

errorPlacement: function (error, el) {
    if (el.attr('name') === 'item[]') {
        error.appendTo('#itemErrors');
    } else {
        error.appendAfter(el);
    }
}

The overall result can be seen at this jsfiddle.

But what if your checkboxes are using different names?

Checkboxes with different names

Here’s another example where the checkbox names are similar:

<form id="checkboxTest">
    <p id="itemErrors"></p>
    <p><label><input type="checkbox" name="item1" value="item 1"> Item #1</label></p>
    <p><label><input type="checkbox" name="item2" value="item 2"> Item #2</label></p>
    <p><label><input type="checkbox" name="item3" value="item 3"> Item #3</label></p>
    <p><input type="submit" name="submit" value="Submit">
</form>

We can tell the rules that each item will be required, but only if there are not enough items already checked.

rules: {
    item1: {
        required: {
            param: true,
            depends: notEnoughItems
        }
    },
    item2: {
        required: {
            param: true,
            depends: notEnoughItems
        }
    },
    item3: {
        required: {
            param: true,
            depends: notEnoughItems
        }
    }
},

There is some duplication here, and with the following messages, but we’ll soon see that removed.

messages: {
    item1: {
        required: "Please select at least two items."
    },
    item2: {
        required: "Please select at least two items."
    },
    item3: {
        required: "Please select at least two items."
    }
},

The separate items are all grouped together, for easier error message handling:

groups: {
    items: "item1 item2 item3"
},

and if their errors match, we’ll place them in the special place for them:

errorPlacement: function (error, el) {
    var groups = $(el.get(0).form).validate().groups;
    if (groups[el.attr('name')] === 'items') {
        error.appendTo('#itemErrors');
    } else {
        error.insertAfter(el);
    }
}

You can see this second example in action at jsfiddle

But how can we reduce duplication of the rules and messages?

Reduced duplication

We can prepare a few variables at the start, for the items and the item names.

var items = $('[name^="item"]'),
    itemNames = [];
items.each(function () {
    itemNames.push(this.name);
});

The validate() function doesn’t have the options for rules and messages any more. Those will be added later.

The groups in the validate() options can now be put together automatically from the itemNames.

$('#checkboxTest').validate({
    groups: {
        items: itemNames.join(' ')
    },

And lastly we get to add the rules and messages, by looping through each item and adding the rules and messages on to each one individually.

function notEnoughItems() {
    return items.filter(':checked').length < 2;
}

items.each(function (index, item) {
    $(item).rules('add', {
        required: {
            param: true,
            depends: notEnoughItems
        },
        messages: {
            required: "Please select at least two items."
        }
    });
});

This example can be seen working at jsfiddle


3 Likes

Thanks
@Paul_Wilkins

@Paul_Wilikins

Although this code is working fine with Single But when I try to Integrate it with my big code its now working

Here is my full code

Help Me some point where is wrong I am not able t figure out
I am not asking WRITE CODE FOR ME

Okay - first step is to visit the JavaScript console (Ctrl+Shift+J) and you’ll see that there’s an error there:

Which comes from:

$("input[name='userDob']").datepicker();

Include jQuery UI as an external resource and that should resolve that particular issue.

I did leave a bug in some of my code, which is the following:

error.insertAfter(element);

There is no element variable, so use el there instead. I’ll fix up the related post for others who may be intending to use it too.

code updated

1)JQueryUI is added
2) “element” is replaced with “el”

Go with jQuery (edge) and not the compat one. That will get datepicker working for you.

Next, let’s go with a better way to reference the form from the field:

var groups = $(el.get(0).form).validate().groups;

And lastly, the action attribute of the form is screwing you up. As a work-around I have used single quotes on there instead.

<form method="post" action="<c:url value='/AddStudent/'>" ...>

That should get things working for you.

@Paul_Wilkins

Hi Paul
Code is updated

Unnecessary JSP code is removed and also css parts.
Now validaton is working fine only thing its not working in check box

Look at the name of those check boxes. Do you have any scripting that supplies validation rules for them?

@Paul_Wilkins

?
Mean

With the checkbox:

<input type="checkbox" name="user10thMarksheet">

You have the following validation rule:

user10thMarkSheet:{
    required: {
        param: true,
        depends: notEnoughItems
    }
},

Which is fine - it will only be required if you don’t have enough items currently selected, so look at the notEnoughItems function.

function notEnoughItems() {
    return $('[name^="item"]:checked').length < 1;
}

Do you see anything in there that is not doing its job properly?

@Paul_Wilkins
Thanks its working

Can you explain meaning of these lines
"
errorPlacement: function (error, el) {
var groups = $(el.get(0).form).validate().groups;
if (groups[el.attr(‘name’)] === ‘items’) {
error.appendTo(‘#itemErrors’);
} else {
error.insertAfter(el);
}
}
}
"

[quote=“vngx, post:13, topic:173112”]
Can you explain meaning of these lines[/quote]

Yes indeed.

errorPlacement: function (error, el) {

This creates a function called errorPlacement. The validator automatically knows to pass all errors that occur through this errorPlacement function. For each error, the validator passes both the error information, and the field on which the error occurred, to this function.

var groups = $(el.get(0).form).validate().groups;

Earlier we defined several fields as belonging to the items group. Here, we are getting all of the groups that the validator knows about.

if (groups[el.attr('name')] === 'items') {

For the error that’s being processed, this line checks if error’s form field is in the group called items.

error.appendTo('#itemErrors');

If the error belonged to the items group, we want to place that particular error in a different location. This location happens to be a div that we’ve identified as itemErrors

} else {
    error.insertAfter(el);
}

If on the otherhand the error does not belong to the items group, the standard default behaviour for all other errors is to place the error message after the field that it happened on.

I hope that helps to explain the meaning of those lines.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.