2011-03-11 59 views
2

我正在做一個非常簡單的驗證,檢查兩個字段是否相等。不幸的是,它似乎沒有工作(當它返回true時返回false)。jQuery驗證問題使用equalTo

這裏是jQuery的(#profSet爲主要形式):

  //if either password field is filled, start trying to validate it 
      if($("#chpw").val() != "" || $("#chpw2").val() != "") 
      { 
       $("#profSet").validate({ 
        rules: { 
         chpw2: { 
          equalTo: "#chpw" 
         } 
        } 
       }); 
       if($("#profSet").valid()) 
       { 
        $pv = 1; 
       } 
       else 
       { 
        $pv = 0; 
       } 
      } 

這裏的HTML:

<tr> 
     <td>Change Password</td><td><input type="password" id="chpw" name="chpw"/></td> 
    </tr> 
    <tr> 
     <td>Confirm Password</td><td><input type="password" id="chpw2" name="chpw2"/><br><label for="chpw2" class="error" generated="true"></label></td> 
    </tr> 

回答

5

我想是這樣

[更新]:對不起,假設答案

<script type="text/javascript" src="scripts/jquery.js"></script> 

<script type="text/javascript" src="scripts/jquery.validate.js"></script> 

<script type="text/javascript"> 
$(function(){ 
    $('#form').validate({ 

     rules:{ 
      chpw:{ 
       required: true, 
       equalTo: '#chpw2' 
      } 

     }, 

     messages:{ 
      chpw: 
       { 
       required: "Password is required", 
       equalTo: "Password must be equal" 
       } 

     }} 
    ) 

}) 


</script> 

<form id="form"> 
    <tr> 
    <td>Change Password</td><td><input type="password" id="chpw" name="chpw"/></td> 
    </tr> 
    <tr> 
    <td>Confirm Password</td><td><input type="password" id="chpw2" name="chpw2"/><br><label for="chpw2" class="error" generated="true"></label></td> 
    </tr> 
<input type="submit" name="submit" /> 
</form> 
+0

它仍然無法正確驗證,它似乎無視我輸入的內容。 – AKor 2011-03-11 07:18:46

+0

@Sennheiser似乎你是正確的開始 – 2011-03-11 10:28:16

2

您可以像波紋管一樣做 -

$("#formId").validate({ 
     rules: { 

      chpw: { 
       required: true, 
       minlength: 6 
      }, 
      chpw2: { 
       required: true, 
       minlength: 6, 
       equalTo: "#chpw" 
      } 
     } 
    }); 

});