jQuery根据另一个元素值验证长度

时间:2014-01-17 10:43:49

标签: jquery jquery-validate

我正在尝试验证表单,有一个需要的ID输入,只有当国籍选择等于特定的一个时,它还需要有14位数,请看一下代码

  jQuery("#msform").validate({
            groups: {
                dob: 'day month year'
            },
            rules: {
                full_name: "required",
                password: {
                    required: true,
                    minlength: 5
                },
                passwordconfirm: {
                    required: true,
                    minlength: 5,
                    equalTo: "#password"
                },
                email: {
                    required: true,
                    email: true
                },
                nationality: "required",
                 id: {
                    required: true,
                    length:{
                        depends: function(element){
                        return ($("#id").val().length == 14 && $("#nationality").val()==61);
                        } 
                    } 
                },
                read: "required"
            },
            messages: {

            },
            errorPlacement: function (error, element) {
                if (element.attr("name") == "day" || element.attr("name") == "month") {
                    error.insertAfter(jQuery("#year"));
                } else {
                    error.insertAfter(element);
                }
            },
            submitHandler: function (form) {
                form.submit();
            }

        });

但这似乎不起作用,当我移出ID输入时,我在控制台中看到以下错误。

Uncaught TypeError: Cannot call method 'call' of undefined 

你知道如何实现这个吗?

由于

1 个答案:

答案 0 :(得分:1)

尝试

        nationality: "required",
        id: {
            required: true,
            minlength: {
                depends: function (element) {
                    return $("#nationality").val() == 61;
                },
                param: 14
            },
            maxlength: {
                depends: function (element) {
                    console.log($("#nationality").val())
                    return $("#nationality").val() == 61;
                },
                param: 14
            }
        }

演示:Fiddle


或添加长度规则

jQuery.validator.addMethod('length', function (value, element, param) {
    var length = $.isArray(value) ? value.length : this.getLength($.trim(value), element);
    return this.optional(element) || length == param;
}, jQuery.validator.format("Please enter {0} characters."))

然后

        nationality: "required",
        id: {
            required: true,
            length: {
                depends: function (element) {
                    return $("#nationality").val() == 61;
                },
                param: 14
            }
        }

演示:Fiddle