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

前端 未结 2 792
遥遥无期
遥遥无期 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".

    
    

    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/

提交回复
热议问题