jQuery Validation - 两个字段,只需要填写一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8137844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:05:40  来源:igfitidea点击:

jQuery Validation - Two fields, only required to fill in one

jqueryjquery-validate

提问by Probocop

I'm using the jQuery Validation Pluginon my form. On my form I have a 'Telephone' field and a 'Mobile No.' field.

我在我的表单上使用jQuery 验证插件。在我的表格上,我有一个“电话”字段和一个“手机号码”。场地。

How would I go about making it so the user has to fill in one of them, but it can be either field?

我将如何制作它以便用户必须填写其中一个,但它可以是任一字段?

回答by Jeff Wilbert

This looks like what you need to use dependency-callback

这看起来像你需要使用依赖回调

What this will allow you to do is:

这将允许您做的是:

Makes the element required, depending on the result of the given callback.

根据给定回调的结果,使元素成为必需的。

You can then place a requiredvalidation rule on the two telephone fields that will only be required based on the return from the function callback; thus you can put a rule on the telephone field to say require this rule only if the mobile field is blank, and vice versa for the mobile field.

然后,您可以required在两个电话字段上放置验证规则,仅根据函数回调的返回值才需要该规则;因此,您可以在电话字段上设置规则,仅当移动字段为空时才需要此规则,反之亦然。

This is untested but in theory

这是未经测试的,但在理论上

rules: {
    telephone: {
        required: function(element) {
            return $("#mobile").is(':empty');
        }
    },
    mobile: {
        required: function(element) {
            return $("#telephone").is(':empty');
        }
    }
}

Be sure to check comments/other answers for possible updated answers.

请务必检查评论/其他答案以获取可能的更新答案。

UPDATE

更新

rules: {
     telephone: {
          required: '#mobile:blank'
     },
     mobile: {
          required: '#telephone:blank'
     }
}

回答by eveevans

I think that the correct way of do this is using the "require_from_group" method.

我认为这样做的正确方法是使用“require_from_group”方法。

You can checkit on http://jqueryvalidation.org/require_from_group-method/

您可以在http://jqueryvalidation.org/require_from_group-method/ 上检查

The example is exactly what your are searching for:

该示例正是您要搜索的内容:

<input class="left phone-group" id="mobile_phone" name="mobile_phone">
<input class="left phone-group" id="home_phone" name="home_phone">
<input class="left phone-group" id="work_phone" name="work_phone">

<script>
$( "#form" ).validate({
  rules: {
    mobile_phone: {
      require_from_group: [1, ".phone-group"]
    },
    home_phone: {
      require_from_group: [1, ".phone-group"]
    },
    work_phone: {
      require_from_group: [1, ".phone-group"]
    }
  }
});
</script>

It's mandatory to include additional-methods.js

必须包含 additional-methods.js

回答by Barbs

Came here looking for the same answers. Found the above post very helpful. Thanks.

来到这里寻找相同的答案。发现上面的帖子很有帮助。谢谢。

I have extended this solution to check if the other field is in fact valid, rather than just "not empty". This ensures that the user inputs a valid Phone Number before removing the "required" class from the Mobile field and vice versa.

我扩展了这个解决方案来检查另一个字段是否实际上有效,而不仅仅是“非空”。这可确保用户在从 Mobile 字段中删除“必需”类之前输入有效的电话号码,反之亦然。

Mobile: {
    required: function(element) {
    return (!$("#Phone").hasClass('valid'));
    }
},
Phone: {
    required: function(element) {
        return (!$("#Mobile").hasClass('valid'));
    }
}

回答by Vik18

Requirement is Validation need to be either C or (A and B) is required. The thing worked for me is:

要求是验证需要是 C 或(A 和 B)是必需的。对我有用的是:

$.validator.addMethod("multipeFieldValidator", function(value) { 
    var returnVal = false; 
    if($("#Cfield").val() != '' || ($("#Afield").val() != '' && $("#Bfield").val() != '')) {
        returnVal = true;
    }
    return returnVal; 
}, 'Either C or A and B is required');


$('#Afield.form-control').change(function(){
    $(this).valid();
    $("#Bfield").valid();
    $("#Cfield").valid();

});

$('#Bfield.form-control').change(function(){
    $(this).valid();
    $("#Afield").valid();
    $("#Cfield").valid();
});

$('#Cfield.form-control').change(function(){
    $(this).valid();
    $("#Bfield").valid();
    $("#Afield").valid();
});


within rules I have 
Afield: "multipeFieldValidator",
Bfield: "multipeFieldValidator",
Cfield: "multipeFieldValidator" 

回答by Vijayan Jayaraman

$(document).ready(function () {
    jQuery.validator.addMethod("mobile10d", function (value, element) {
        return this.optional(element) || /^[7-9]{1}[0-9]{9}$/.test(value);
    }, "Please enter a valid 10 digit phone number.");
    $("#form_id").validate({
        rules: {
            mobile: {
                required: "#telephone:blank",
                mobile10d: true
            },
            telephone: {
                required: "#mobile:blank",
                mobile10d: true
            }
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form class="" action="" method="POST" id="form_id">
    <div class="col-md-4 form-group">
        <label class="form-control">Mobile<span class="required">*</span></label>
        <input class="form-control" type="text" name="mobile" id="mobile" placeholder="0-9">
    </div>
    <div class="col-md-4 form-group">
        <label class="form-control">Telephone<span class="required">*</span></label>
        <input class="form-control" type="text" name="telephone" id="telephone" placeholder="0-9">
    </div>
    <div class="form-group">
        <input type="submit" name="" value="Submit" class="apply-now-btn">
    </div>
</form>

回答by Salim Ali

This Will do

这会做

Mobile: {
    required: function(element) {
    return (jQuery.isEmptyObject($("#Phone").val()));
    }
},
Phone: {
    required: function(element) {
        return (jQuery.isEmptyObject($("#Mobile").val()));
    }
}

回答by Warren

I had troubles is .is(':empty')so here is my working options example.

我遇到了麻烦,.is(':empty')所以这里是我的工作选项示例。

Before:

前:

rules: {
   name:       {required: true},
   email:      {required: true},
   phone:      {required: true}
}

All fields wererequired. But I wanted email and/or phone so to create the 'or':

所有字段都是必需的。但我想要电子邮件和/或电话,以便创建“或”:

rules: {
   name:       {required: true},
   email:      {required: 
                    function() {
                        //returns true if phone is empty   
                        return !$("#phone").val();
                    }
               },
   phone:      {required:
                    function() {
                        //returns true if email is empty
                        return !$("#email").val();
                     }
               }
},
messages: {
   email: "Email is required if no phone number is given.",
   phone: "A phone number is required if no phone email is given."
}

And you will see that I've added the messagesoption to give the user some meaningful info because the default messages would say that each field is required which is not true in this situation.

你会看到我已经添加了messages为用户提供一些有意义的信息的选项,因为默认消息会说每个字段都是必需的,这在这种情况下是不正确的。