成功时无法使jQuery正确显示有效的类

时间:2012-11-29 20:30:54

标签: javascript jquery validation

我在验证表单时遇到了一些问题:

  • 验证返回错误时,会显示span元素 包含交叉图像和消息,这是预期的。

  • ,当验证成功时,会显示多个范围元素会显示另一个 < / strong>,包含复选标记图片(抱歉,无法上传图片,因为我是新手)。

代码:

jQuery验证:

$("#signupform").validate({...
    errorClass: "error",
    validClass: "valid",
    errorElement: "span",

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

    unhighlight: function(element, errorClass) {
        $(element).removeClass(errorClass);
    },

    success: function(label) {
        label.addClass('valid').removeClass('error');
    }
});​

HTML表格:

                   ...          
<div class="field">
   <label for="email">Email:</label>
   <input type="text" id="email" name="email" />                    
   <span id="email_status"></span>  
</div>
<div class="field">
   <label for="username">Username:</label>
   <input type="text" id="username" name="username" />  
   <span id="username_status"></span>   
</div>
<div class="field">
   <label for="password">Password:</label>
   <input type="text" id="password" name="password" />                      
</div>
<div class="field">
   <label for="confirmPassword">Confirm password:</label>
   <input type="password" id="confirmPassword" name="confirmPassword" />                    
</div>
...

注意:“email_status”和“username_status”特定于ajax可用性验证。

CSS:

#signupform span{  
    width:auto;
    height:16px;
    padding-left:30px;  
    margin-left:10px; 
    display:inline-block;
    vertical-align:text-bottom;
    font-family: Avant Garde, Arial,sans-serif;
    font-size:12px;
    border:1px solid #000;
}


#signupform span.valid  {
  background:url("../images/tick.png") left center no-repeat;
}

#signupform  span.error{
  background:url("../images/error.png") left center no-repeat;
  color:#B94A48; 
}

出了什么问题?

1 个答案:

答案 0 :(得分:1)

在成功功能中添加检查条件..

success: function(label) {
    if(!label.hasClass('valid')){
        label.addClass('valid')
    }
    label.removeClass('error');
}

更新代码

$("#signupform").validate({
    rules: {
        password: "required"
    },
    messages: {
        password: {
            required: "Este campo es requerido."
        }
    },
    errorClass: "error",
    validClass: "valid",
    errorElement: "span",
    highlight: function(element, errorClass, validClass) {
        $('.field span').remove();
        $(element).addClass(errorClass).removeClass(validClass);
    },
    unhighlight: function(element, errorClass) {
        $(element).removeClass(errorClass);
    },
    success: function(label) {
        $('.field span:gt(0)').remove();
        var $label = $(label);
        if (!$label.hasClass('valid')) {
            $label.addClass('valid');
        }
        $label.removeClass('error');
    }
});​

<强> Check Fiddle