JQuery Validation <select> min depends on other field, not working

前端 未结 2 793
遥遥无期
遥遥无期 2021-01-07 17:16

I have a select \"ArrearsLHOLocation\" that has an option \"None Selected\" with a value of -1 and all other selectable values are greater than 0.

Here is the rule d

相关标签:
2条回答
  • 2021-01-07 17:49

    A select can only be required or not. I've never seen the min rule used on a select to force the user to choose an option.

    Your "None Selected" option should contain value="" and then when you declare the required rule on this, the user will be forced to select any option other than "None Selected".

    <select name="list">
        <option value="">None Selected</option>
        <option value="1">option 1</option>
        <option value="2">option 2</option>
        <option value="3">option 3</option>
    </select>
    

    Then your depends parameter would simply need to return a boolean to state whether the user needs to select an option.

    $('[name="list"]').rules("add", {
        required: {
            depends: function (elem) {
                return $("#check").is(":checked");
            }
        },
        messages: {
            required: "Select from the list"
        }
    });
    

    DEMO: http://jsfiddle.net/7k2zg7rv/


    EDIT:

    Since you want to keep your first option as value="-1", you'll need to create a custom rule/method using the addMethod() method that recognizes your first option as invalid.

    $.validator.addMethod('select', function(value, element) {
        return (value == -1) ? false : true;
    });
    

    Updated DEMO: http://jsfiddle.net/7k2zg7rv/2/

    0 讨论(0)
  • 2021-01-07 17:53

    Looking at jquery.validate I found that depends should only ever evaluate to true/false. So modifying the min to have [param : 0] which would have been the min when I needed it. Then changing the depends to evaluate to true when the minimum should be in effect solved this issue.

    $("#ArrearsLHOLocation").rules("add", {
            min: {
                param: 0,
                depends: function (elem) {
                    return $("#rbArrearsLHO[value='True']").is(":checked");
                }
            },
            messages: {
                min: "You have stated that the applicant/coapplicant have LHO arrears but you have not stated where!"
            }
        });
    

    DEMO: FIDDLE (forked from @Sparky's previous fiddle)

    0 讨论(0)
提交回复
热议问题