jquery validator - Validating visible elements only

时间秒杀一切 提交于 2019-12-12 07:15:44

问题


I have a radiobutton that hides/shows a div. All visible elements are "required", but adding ignore: ":hidden" after the validation rules, doesn't work... Here's the code:

<script type="text/javascript">

        $(document).ready(function(){
            $("#myForm").validate({
                rules: {
                    name: "required",
                    age: "required",
                    height: "required",
                    ignore: ":hidden"
                }
            })
        });

    </script>
</head>
<body>
    <form id="myForm" name="myForm" method="post" action="" >
        <input type="radio" name="checkAge" value="adult" onclick="$('#minorRequisites').hide();" />Adult<br/>
        <input type="radio" name="checkAge" value="minor" onclick="$('#minorRequisites').show()" checked="checked"/>Child<br/>
        Name <input id="name" name="name" type="text" /><br/>
        <div id="minorRequisites">
            Age <input id="age" name="age" type="text" /><br/>
            Height <input id="height" name="height" type="text" /><br/>
        </div>
        <input type="submit" />
    </form>
</body>

I want to be able to submit the form giving only name if "Adult" is checked... Any ideas? :)


回答1:


You can specify dependency expressions in your required rules to have them ignore the elements if they're not visible:

$("#myForm").validate({
    rules: {
        name: "required",
        age: {
            required: "#age:visible"
        },
        height: {
            required: "#height:visible"
        }
    }
});

You can see the results in this fiddle.

EDIT: ignore will also work, but it's an option, not a rule, so you should write:

$("#myForm").validate({
    ignore: ":hidden",
    rules: {
        name: "required",
        age: "required",
        height: "required"
    }
});



回答2:


Please try ignore: ":not(:visible)" instead of ignore: ":hidden".



来源:https://stackoverflow.com/questions/7349902/jquery-validator-validating-visible-elements-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!