jQuery Validate - Only allow one out of two

前端 未结 4 424
我在风中等你
我在风中等你 2021-01-14 07:37

Need a little help. So got a form, where I\'ve got two fields mobile and telephone. Only one is required. My code below does that, but what I would like is I don\'t want peo

4条回答
  •  半阙折子戏
    2021-01-14 08:14

    This solution uses standard functionality from the Validation plugin. I used the require_from_group rule to make sure at least one is filled, and then I used the maxlength rule to disallow one if the other is filled. Just make sure the phone-group class is added to both input fields to support the require_from_group rule.

    $("form").validate({
        rules: {
            mobile: {
                require_from_group: [1, ".phone-group"], 
                maxlength: {param: 0, depends: "#telephone:filled"}
            },
            telephone: {
                require_from_group: [1, ".phone-group"], 
                maxlength: {param: 0, depends: "#mobile:filled"}
            }
        },
        messages: {
            mobile: "Please enter either a telephone number or a mobile number.",
            telephone: "Please enter either a telephone number or a mobile number."
        }
    });
    

提交回复
热议问题