jQuery ValidationEngine:如何验证一组字段中至少有一个不为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4971022/
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-26 18:18:41  来源:igfitidea点击:

jQuery ValidationEngine: How to validate that at least one of a set of fields is not empty?

jqueryjquery-validation-engine

提问by Dmitriy Sosunov

In our project we are using ValidationEngine, and we don't have the ability to replace it with another plug-in.

在我们的项目中,我们使用的是 ValidationEngine,我们无法将其替换为其他插件。

Our form has ten inputs and some of them are optional, but at least one of the optional fields must be included.

我们的表单有十个输入,其中一些是可选的,但必须至少包含一个可选字段。

So, how do you validate inputs in this case?

那么,在这种情况下如何验证输入?

Sample:

样本:

form
  input1
  input2
  intpu3

input1: required

输入 1:必需

At least one of input2 and input3 must be present -- if both are empty validation should fail.

必须至少存在 input2 和 input3 之一——如果两者都是空的,验证应该失败。

回答by Terrance

The validation engine now supports group Validation.Go to jQuery form validation plugin @ githuband ake a look at groupRequired. The syntax looks something like this.

验证引擎现在支持组验证。转到jQuery 表单验证插件@github并查看groupRequired. 语法看起来像这样。

<input value="" class="validate[groupRequired[payments]]" type="text" name="creditcard" id="creditcard" />
<input class="validate[groupRequired[payments]]" type="text" id="paypal" name="paypal"/>

回答by jessegavin

It appears that the ValidationEngine plugin allows you to specify a validation rule which uses a custom function to determine validity.

ValidationEngine 插件似乎允许您指定使用自定义函数来确定有效性的验证规则。

If you add the validate class on input1like so...

如果你input1像这样添加验证类......

<input id="input1" class="validate[required,funcCall[myValidationFunction]]" />

Then ValidationEngine will use the following function. You can pretty much put any kind of logic in there. If I read your scenario correctly, this should accomplish what you're after.

然后 ValidationEngine 将使用以下函数。您几乎可以在其中放置任何类型的逻辑。如果我正确阅读了您的场景,这应该可以完成您的任务。

function myValidationFunction() {
  var input1 = $.trim($("#input1").val());
  var input2 = $.trim($("#input2").val());
  var input3 = $.trim($("#input3").val());

  if (input1.length == 0) {
    return "input1 is required";
  }

  if (input2.length == 0 && input3.length == 0) {
    return "Either input2 or input3 is required";
  }

  // We don't need to return anything if there is no error.
}

Here's a link to the _funcCallfunction in the source code: https://github.com/posabsolute/jQuery-Validation-Engine/blob/master/js/jquery.validationEngine.js#L574

这是_funcCall源代码中该函数的链接:https: //github.com/posabsolute/jQuery-Validation-Engine/blob/master/js/jquery.validationEngine.js#L574

回答by Andrew Feng

In case someone wants to make groupRequired work for checkboxes, you need to add error messages to your language file for groupRequired. e.g. if it is jquery.validationEngine-en.js, it should be like this:

如果有人想让 groupRequired 为复选框工作,您需要将错误消息添加到 groupRequired 的语言文件中。例如,如果它是 jquery.validationEngine-en.js,它应该是这样的:

"groupRequired": {
  "regex": "none",
  "alertText": "* You must fill one of the following fields",
  "alertTextCheckboxMultiple": "* Please select an option",
  "alertTextCheckboxe": "* This checkbox is required"
}

回答by Mark Kahn

!!$('#input2,#input3').filter('[value]').length

回答by ChrisThompson

One solution could be to attach validations before validating and removing after validation is over.

一种解决方案可能是在验证之前附加验证并在验证结束后删除。

jQuery(document).ready(function(){
    jQuery("#formID").validationEngine();

    $("#formID").bind("jqv.form.validating", function(event){
        var fieldsWithValue = $('input[type=text]').filter(function(){
            if($(this).val().length>0){
                return true;
            }
        });
        if(fieldsWithValue.length<1){
            $('input[type=text]').addClass('validate[required,funcCall[requiredOneOfGroup]]');
        }
    });

    $("#formID").bind("jqv.form.result", function(event, errorFound){
        $('input[type=text]').removeClass('validate[required,funcCall[requiredOneOfGroup]]');
    });
});

function requiredOneOfGroup(field, rules, i, options){
    var fieldsWithValue = $('input[type=text]').filter(function(){
        if($(this).val().length>0){
            return true;
        }
    });
    if(fieldsWithValue.length<1){
        return "At least one field in this set must have a value.";
    }
}

回答by Vicky

There is a provision in jquery validation plugin to make grope of of elements.

jquery 验证插件中有一项规定可以对元素进行摸索。

groups: {groupName: "text1 text2 text3 .. so on"}

errorPlacement: function(error, element) {
                    // Write Done your business logic to display error 

             if ( element.attr("name") == "text1" -- define other text elements also) {
               error.insertAfter("#error_location_placeholder_id");
                    }else{
               error.insertAfter(element);
             }               

           }

and you business validation in rules method for at least one must be not empty logic

并且您在规则方法中的至少一个业务验证必须不是空逻辑

groupName:{

                    required: function(element) {
// Your business logic for validation

                        if( $("#text1").val().length > 0 ){
                            return false;
                        }else{
                            return true;
                        }

                    }
                }