Custom Validation on jquery validate plugin, need to count element in a multiple select
I have a multiple select, and I need to force the user to choose maximum two options, nothing more.
I'm trying this:
jQuery.validator.addMethod("morethantwo",
function(value, element) {
var foo = [];
$(element+' :selected').each(function(i, select开发者_开发问答ed){
foo[i] = $(selected).text();
alert(foo[i]);
});
return true;
},"Max two options."
);
The problem is that I get a:
uncaught exception: Syntax error, unrecognized expression: [object HTMLSelectElement]
error. While if I do this:
$(element).each(function(i, selected){
foo[i] = $(selected).text();
alert(foo[i]);
});
It works but I get all the options in the select. Why is that? Is this the correct road to walk? Are there better ways to do this kind of check?
Thank you very much!
To answer the why it's breaking, element
is a DOM element, not a string, so in that code you're trying to do DOMElement+string
...which doesn't work :) Instead wrap the DOM element and use .find()
or .children()
to get the options.
Knowing why it broke, you can write your rule like this to check the selected options:
jQuery.validator.addMethod("maxtwo", function(value, element) {
return $(element).find(":selected").length <= 2;
},"Max two options.");
Check here for a demo of the above code
If you're strictly dealing with a <select multiple>
you could do this as well:
return $(element).val().length <= 2;
Since .val()
returns an array in that case.
精彩评论