jQuery Validate,在两个空白字段中,必须至少填写一个字段或两者都填写

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

jQuery Validate, out of two blank fields, at least one field must be filled or both

jqueryjquery-validate

提问by bigZero

I want to validate my form so that is out of two blank fields, at least one field must be filled and two fields also can be filled; but can't leave any field blank.

我想验证我的表格,以便在两个空白字段之外,至少必须填写一个字段,也可以填写两个字段;但不能将任何字段留空。

I'm using jquery-1.9.1-min.js and here is my html page.

我正在使用 jquery-1.9.1-min.js,这是我的 html 页面。

<form action="#" class="send_form" id="forgot_pass_form" method="POST">
            <fieldset>
                <div class="send_row">
                    <label class="padding-top10">Email</label>
                    <input type="text" class="send_email" id="email" name="email" />
                    <em>You need to type an email address</em>
                </div>

                <div class="send_row option">OR</div>

                <div class="send_row">
                    <label class="padding-top10">Username</label>
                    <input type="text" class="send_username" id="uname" name="uname" />
                </div>


                <div class="send_row send_submitforgotuser">
                    <input type="submit" value="Submit" />
                </div>
            </fieldset>
            </form>

Any suggestion how to do it.... ?

任何建议如何做到这一点....?

sofar I have tried

到目前为止我已经尝试过

 jQuery.validator.addMethod("require_from_group", function(value, element, options) {
    alert("xxx");
    var valid = $(options[1], element.form).filter(function() {
        return $(this).val();
    }).length >= options[0];

    if(!$(element).data('reval')) {
        var fields = $(options[1], element.form);
        fields.data('reval', true).valid();
        fields.data('reval', false);
    }
    return valid;
}, jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields."));

Still not getting friutful output.

仍然没有得到富有成效的输出。

回答by Sparky

You are attempting to use validator.addMethodwhich is part of the jQuery Validate plugin. You'll need to include this plugin in your code if you haven't already.

您正在尝试使用validator.addMethod它的一部分的jQuery验证插件。如果你还没有,你需要在你的代码中包含这个插件。

Then use the require_from_grouprule that's already part of the Validate plugin's additional-methods.jsfile. (Don't forget to include the additional-methods.jsfile too.)

然后使用require_from_group已经是 Validate 插件additional-methods.js文件的一部分的规则。(不要忘记也包含该additional-methods.js文件。)

rules: {
    myfieldname: {
        require_from_group: [1, ".class"]
    }
}
  • First parameter is the number of items to be required.
  • Second parameter is the classassigned to all elements in your grouping. I added a sendclass to your two input elements.

  • Also use the groupsoptionto consolidate the two messages into one.

  • 第一个参数是需要的项目数。
  • 第二个参数是class分配给分组中的所有元素。我send为您的两个输入元素添加了一个类。

  • 还可以使用groups选项将两个消息合并为一个。

jQuery:

jQuery

$(document).ready(function () {

    $('#forgot_pass_form').validate({ // initialize the plugin
        groups: {  // consolidate messages into one
            names: "uname email"
        },
        rules: {
            uname: {
                require_from_group: [1, ".send"]
            },
            email: {
                require_from_group: [1, ".send"]
            }
        }
    });

    //  for your custom message
    jQuery.extend(jQuery.validator.messages, {
        require_from_group: jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.")
    });

});

Working Demo: http://jsfiddle.net/sgmvY/1/

工作演示:http: //jsfiddle.net/sgmvY/1/



EDIT: As per Github, there is an open issuewith the require_from_groupmethod. Until it's fixed, the developer is recommending this solution below. Since you would manually add the revised method into your code, there is no need to include the additional-methods.jsfile.

编辑根据 Github,require_from_group方法存在一个未解决的问题。在修复之前,开发人员在下面推荐此解决方案。由于您将手动将修改后的方法添加到您的代码中,因此无需包含该additional-methods.js文件。

New Working Demo: http://jsfiddle.net/kE7DR/2/

新的工作演示:http: //jsfiddle.net/kE7DR/2/

$(document).ready(function () {

    jQuery.validator.addMethod("require_from_group", function (value, element, options) {
        var numberRequired = options[0];
        var selector = options[1];
        var fields = $(selector, element.form);
        var filled_fields = fields.filter(function () {
            // it's more clear to compare with empty string
            return $(this).val() != "";
        });
        var empty_fields = fields.not(filled_fields);
        // we will mark only first empty field as invalid
        if (filled_fields.length < numberRequired && empty_fields[0] == element) {
            return false;
        }
        return true;
        // {0} below is the 0th item in the options field
    }, jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields."));

    $('#forgot_pass_form').validate({ // initialize the plugin
        groups: {
            names: "uname email"
        },
        rules: {
            uname: {
                require_from_group: [1, ".send"]
            },
            email: {
                require_from_group: [1, ".send"]
            }
        }
    });



});

回答by Glyn

@Sparky I am trying to use your answer to validate the update of an Account name and/or Password. I enter in the original Account Name and Password and then click on the update button and the validation of the original Account name and Password is performed (i.e., no message to say that a new Account or Password must be entered). My code is:

@Sparky 我正在尝试使用您的答案来验证帐户名和/或密码的更新。我输入原始帐户名和密码,然后单击更新按钮,并执行原始帐户名和密码的验证(即,没有消息说必须输入新帐户或密码)。我的代码是:

$(document).ready(function(){
$.validator.addMethod(
        "regex",
        function(value, element, regexp) 
        {
            if (regexp.constructor != RegExp)
                regexp = new RegExp(regexp);
            else if (regexp.global)
                regexp.lastIndex = 0;
            return this.optional(element) || regexp.test(value);
        },
        "Please enter correct Characters."
);
jQuery.validator.addMethod("require_from_group", function (value, element, options) {
    var numberRequired = options[0];
    var selector = options[1];
    var fields = $(selector, element.form);
    var filled_fields = fields.filter(function () {
        // it's more clear to compare with empty string
        return $(this).val() != "";
    });
    var empty_fields = fields.not(filled_fields);
    // we will mark only first empty field as invalid
    if (filled_fields.length < numberRequired && empty_fields[0] == element) {
        return false;
    }
    return true;
    // {0} below is the 0th item in the options field
}, jQuery.format("'Please enter either a new Account name and/or a new password'/Please fill out at least {0} of these fields."));
$('[data-toggle="tooltip"]').tooltip();
$("#contactForm").validate({
    groups: {  // consolidate messages into one
        names: "accountName1 enterPassword1"
    },
    rules: {
        accountName: {
            required: true,
            minlength: 2
        },

        enterPassword: {
            required: true,
            minlength: 8
        },

        accountName1: {
            require_from_group: [1, ".send"],
            minlength: 2
        },

        accountName2: {
            minlength: 2,
            equalTo: "#accountName1"
        },

        enterPassword1: {
            require_from_group: [1, ".send"],
            regex: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/,
            minlength: 8
        },

        enterPassword2: {
            regex: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/,
            minlength: 8,
            equalTo: "#enterPassword1"
        }
    },

    messages: {
        accountName: {
            required: "Please enter your current account name.",
            minlength: "Your account name must consist of at least 2 characters."
        },

        enterPassword: {
            required: "Please enter your current password.",
            minlength: "Your password must consist of at least 8 characters."
        },

        accountName1: {
            minlength: "Your account name must consist of at least 2 characters."
        },

        accountName2: {
            minlength: "Your account name must consist of at least 2 characters.",
            equalTo: "Your confirmation account name does not match the original."
        },

        enterPassword1: {
            regex: "Please nter at least 8 characters containing at least 1 lower case, 1 upercase, 1 special and 1 numeric..",
            minlength: "Your password must consist of at least 8 characters."
        },

        enterPassword2: {
            regex: "Please enter at least 8 characters containing at least 1 lower case, 1 upercase, 1 special and 1 numeric..",
            minlength: "Your password must consist of at least 8 characters.",
            equalTo: "Your confirmation password does not match the original."
        }
    },

    submitHandler : function(contactForm) {
        //do something here
        var frm = $('#contactForm');
        //alert($("#accountName1").val());

        $.ajax({
            type: "POST",
            url: "UpdateAccountView",
            cache: false,
            data: frm.serialize(),
            success: function(data){
                console.log('Submission was successful.');
                console.log(data);

                $("#accountName").focus();
                $('#ajaxGetUserServletResponse').text(data);
            }
        });
    }
});      
}); // end document.ready