jquery.validate略有问题

时间:2013-12-31 08:55:23

标签: jquery twitter-bootstrap jquery-validate

我正在使用jquery验证这是我的问题。一切都按预期验证,但是如果我有5个字段并且都有错误它们会得到错误类,只要一个正确,错误消息就会保留在其余部分上但是错误类被删除并替换为所有输入上的validclass

的.js

    $("#commentForm").validate({
                errorElement : "span",
                validClass : "has-success",
                errorClass : "has-error",
                errorPlacement : function(error, element) {
                    error.appendTo(element.parent("div").next("span"));
                },
                highlight : function(element, errorClass, validClass) {
                    $('div').addClass(errorClass).removeClass(validClass);
                },
                unhighlight : function(element, errorClass, validClass) {
                    $('div').removeClass(errorClass).addClass(validClass);
                },
                rules : {
                    emailfield : {
                        required : true,
                        email : true,
                        minlength : 3
                    },
                    namefield : {
                        required : true,
                        minlength : 3
                    },
                    urlfield : {
                        required : true,
                        minlength : 3,
                        url : true
                    }
                }
            });

html的

    <div class="input-group margin-bottom-sm">
        <span class="input-group-addon input-sm"><i class="fa fa-envelope-o fa-fw"></i></span>
        <input class="form-control input-sm required email" type="text" placeholder="Email address" id="emailfield" name="emailfield">
    </div>
    <span class="help-block"></span>

    <div class="input-group margin-bottom-sm">
        <span class="input-group-addon input-sm"><i class="fa fa-users fa-fw"></i></span>
        <input class="form-control input-sm required" type="text" placeholder="Name" id="namefield" name="namefield">
    </div>
    <span class="help-block"></span>

1 个答案:

答案 0 :(得分:1)

需要定位当前element的div父级,请尝试

highlight: function (element, errorClass, validClass) {
    $(element).closest('div').addClass(errorClass).removeClass(validClass);
},
unhighlight: function (element, errorClass, validClass) {
    $(element).closest('div').removeClass(errorClass).addClass(validClass);
},

演示:Fiddle