Validating multiselect with jquery validation plugin

后端 未结 2 1738
青春惊慌失措
青春惊慌失措 2020-12-21 09:15

Trying to figure out why my recipient multiselect isn\'t validating on form submission. Should be atleast 1 person chosen. I have it set to be required true but yet its stil

相关标签:
2条回答
  • 2020-12-21 09:33

    You can use the following code to validate the single selection required.

    The magic happens in this line:

    ignore: ':hidden:not("#mySelect")'
    

    It's necessary because as default jQuery Validate ignores hidden fields...

    HTML

    <form action="some/action" id="myForm" method="POST">
    
        Select: <select class="someSelect" name="mySelect" id="mySelect" multiple="multiple">
            <option value="some_val1">Some Value</option>
            <option value="some_val2">Some Other Value</option>
        </select>
    
        <input type="submit" value="Submit" />
    
    </form>
    

    Javascript/jQuery

    $(document).ready(function() {
        $('#mySelect').multiselect({
            noneSelectedText: 'Select Something (required)',
            selectedList: 3,
            classes: 'my-select'
        });
    
        $.validator.addMethod("needsSelection", function(value, element) {
            return $(element).multiselect("getChecked").length > 0;
        });
    
        $.validator.messages.needsSelection = 'You gotta pick something.';
    
        $('#myForm').validate({
        rules: {
            mySelect: "required needsSelection",
            input1: "required isPercent",
            input2: "required",
            input3: "required"
        },
        ignore: ':hidden:not("#mySelect")', // Tells the validator to check the hidden select
        errorClass: 'invalid'
        });
    });
    
    0 讨论(0)
  • 2020-12-21 09:46

    The accepted answer doesn't work anymore. The problem is that the "getChecked" argument doesn't do anything anymore. Here is an updated, working version of the validation method

    $.validator.addMethod("needsSelection", function (value, element) {
                    var count = $(element).find('option:selected').length;
                    return count > 0;
                })
    
    0 讨论(0)
提交回复
热议问题