开发者

How to add custom form validation using Jquery Validation Plugin for multiselect input?

开发者 https://www.devze.com 2023-03-01 16:07 出处:网络
I need to create a custom jquery form validation using Jquery Validation Plugin where the multiselect option has following kind of values:

I need to create a custom jquery form validation using Jquery Validation Plugin where the multiselect option has following kind of values:

  • Code1(A)
  • Code2(A)
  • Code3(B)
  • Code4(C)
  • Code5(A)
  • Code6(B)
  • Code7(C)

<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

0

精彩评论

暂无评论...
验证码 换一张
取 消