I need to create a custom jquery form validation using Jquery Validation Plugin where the multiselect option has following kind of values:
<select id="code_ids" multiple="multiple" name="codes[code_ids][]">
<option value="1">Code1(A)</option>
<option value="2">Code2(A)</option>
<option value="3">Code3(B)</option>
<option value="4">Code4(C)</option>
<option value="5">Code5(A)</option>
<option value="6">Code6(B)</option>
<option value="7">Code7(C)</option>
</select>
The custom validation needs to specify that the options must include atleast two options from A, one from B and two from C. I think I need to use Regex to compare the names of the selected options to check whether they belong to A, B or C.
Also, please specify any article or resources that explain the creation of Custom Form Validations using Jquery Validation Plugin. Thanks in advance.
there is addMethod in jquery validate
the html
<form id="myform" action="#" method="post" name="myform">
<select id="code_ids" multiple="multiple" class="meets" name="codes[code_ids][]">
<option value="1">
Code1(A)
</option>
<option value="2">
Code2(A)
</option>
<option value="3">
Code3(B)
</option>
<option value="4">
Code4(C)
</option>
<option value="5">
Code5(A)
</option>
<option value="6">
Code6(B)
</option>
<option value="7">
Code7(C)
</option>
</select>
<input id="test" type="submit" value="submit">
</form>
and the jQuery
$.validator.addMethod("meets", function(value,element) {
var txt = $('option:selected',element).text();
var a = txt.match(/\(A\)/g);
var b = txt.match(/\(B\)/g);
var c = txt.match(/\(C\)/g);
if(a && b && c){
if(a.length >1 && b.length > 0 && c.length > 1 ) {
return true;
}else{
return false;
}
}else{
return false;
}
}, "you have not selected enough eleemnts from each group");
$("#myform").validate()
and a WORKING DEMO