jQuery 验证没有值或长度为 4 个字符

jQuery validation either no value or length of 4 characters

我想知道是否可以将 jQuery 验证属性设置为在文本框中没有值时跳过验证,或者如果有某个值则该值应恰好为 4 个字符。

类似于:

txtObject: {
                     //put validation properties here
                    },

这可能吗?

I would like to know if it's possible to set the jQuery validate properties to either skip validation if there is no value in the textbox or if there is some value then the value should be exactly 4 characters.

当字段为空时跳过验证仅仅意味着您不应该使用 required 规则;使字段 "optional".

仅当字段不为空时才评估所有其他规则。

minlengthmaxlength 规则设置为 4 将符合您的规范。

$(document).ready(function() {  // <-- ensure form's HTML is ready

    $("#test-form").validate({  // <-- initialize plugin on the form.
        // your rules and other options,
        rules: {
            field_name: {  // <-- this is the name attribute, NOT id
                minlength: 4,
                maxlength: 4
            }
        }
    });

});

工作演示:http://jsfiddle.net/5v2cspp7/

        txt_edit_pass_werk_email: 
        {
            minlength: function(element){
                if($("#txt_edit_pass_werk_email").val() != "")
                {
                    return 8;
                }
                else
                {
                    return 0;
                }
            },
            maxlength: 12
        }

我确实遇到了和你一样的问题。所以我确实找到了这个post。我自己想出来了。所以这是使用 jquery 验证和条件字段非常适合我的解决方案: 如果字段 txt_edit_pass_werk_email 不为空.. 则该字段具有最小长度 8 的验证。如果该字段为空,则最小长度为零。这是条件验证。