jQuery Validate plugin : Only one field required out of multiple [closed]

点点圈 提交于 2019-12-13 11:11:29

问题


Wrt this question on stackoverflow , if the telephone and mobile fields are empty then it gives an error message but after that when either of the two is filled and the form is submittted again then too the error message remains . The validation check takes place with the old value of the input and when the page is refreshed then it takes new values. I will be grateful if anyone can help me fixing this problem ??


回答1:


1) As per the question you've linked, I constructed this jsFiddle using the depends option and still see lots of issues. The rules do not seem to work at all, where both fields are always required.

2) There is a require_from_group rule included in the additional-methods.js file. The two fields must have the same class for the rule to target, in this case, .group. But this method has some known bugs where it disables all of the other rules on the form

DEMO: http://jsfiddle.net/SvSrR/

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        groups: {
            name: "telephone mobile"
        },
        rules: {
            telephone: {
                require_from_group: [1, '.group']
            },
            mobile: {
                require_from_group: [1, '.group']
            }
        }
    });

});

3) Instead, I constructed a custom rule called customrule (you can name it however you want) and it's working as I believe it should. I also used the groups option to combine the two error messages into one.

Working DEMO: http://jsfiddle.net/2g8hL/

$(document).ready(function () {

    $.validator.addMethod("customrule", function (value, element) {
        return (!($("#mobile").val() === '') || !($("#telephone").val() === ''));
    }, "please fill out at least one");

    $('#myform').validate({ // initialize the plugin
        groups: {
            name: "telephone mobile"
        },
        rules: {
            telephone: {
                customrule: true
            },
            mobile: {
                customrule: true
            }
        }
    });

});



回答2:


try to put custom error placement

$('#form').validate({
    errorPlacement: function(error,element) {
                       return true;
                    }
});


来源:https://stackoverflow.com/questions/15293332/jquery-validate-plugin-only-one-field-required-out-of-multiple

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