0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.