2014-07-22 17 views
0

使用jQuery驗證插件時,使用.valid()時使用規則和方法的正確方法是什麼?我以前曾經使用.validate(),但由於我不得不在表格外部保留一個按鈕,因此我被迫切換到使用.valid()。但現在,我沒有像以前那樣得到那些自定義錯誤信息。我如何得到這個權利?jQuery Validation插件在使用.valid()時使用規則和消息

我懷疑,我使用的方式.valid()是錯誤的。我嘗試了可能的事情,但都失敗了。

<!DOCTYPE HTML> 
<html> 
<head> 

<title>Test Validation Plugin</title> 

<script type="text/javascript" src="/resources/scripts/jq.js"></script> 
<script type="text/javascript" src="/resources/scripts/temp.js"></script> 
<script type="text/javascript" src="/resources/scripts/validate.js"></script> 

<body> 
    <form id="createAccount"> 
     <input type="text" class="titlea" name="titlea" value="" autocomplete="off"> 
     <label for="titlea" generated="true" class="error titlea" style=""></label> 

     <br> 
     <br> 

     <input type="text" class="titleb" name="titleb" value="" autocomplete="off"> 
     <label for="titleb" generated="true" class="error titleb" style=""></label> 

    </form> 

    <br> 

    <button id="btn">Process</button> 

</body> 
</html> 

jQuery代碼

$('#btn').click(function() { 
    rules: { 
     titlea: { 
      required: true, 
      minlength: 5, 
      maxlength: 24 
     }, 
     titleb: { 
      required: true, 
      minlength: 5, 
      maxlength: 24 
     }, 
    }, 
    messages: { 
     titlea: { 
      required: 'Please choose a title', 
      minlength: 'Title A should be at least 5 characters', 
      maxlength: 'Title A cannot exceed 24 characters' 
     }, 
     titleb: { 
      required: 'Please choose a title', 
      minlength: 'Title B should be at least 5 characters', 
      maxlength: 'Title B cannot exceed 24 characters' 
     }, 
    } 

    ('#createAccount').valid() { // Is this where the problem is? 
     // Submit the form using jQuery ajax 
    } 
}); 

回答

1

有許多語法問題,它應該是

//register the validator 
$('#createAccount').validate({ 
    rules: { 
     titlea: { 
      required: true, 
      minlength: 5, 
      maxlength: 24 
     }, 
     titleb: { 
      required: true, 
      minlength: 5, 
      maxlength: 24 
     }, 
    }, 
    messages: { 
     titlea: { 
      required: 'Please choose a title', 
      minlength: 'Title A should be at least 5 characters', 
      maxlength: 'Title A cannot exceed 24 characters' 
     }, 
     titleb: { 
      required: 'Please choose a title', 
      minlength: 'Title B should be at least 5 characters', 
      maxlength: 'Title B cannot exceed 24 characters' 
     }, 
    } 
}); 

$('#btn').click(function (e) { 
    //check validate 
    if ($('#createAccount').valid()) { 
     e.preventDefault() 
    } 
}); 
+0

確定。所以'.validate'和'.valid'需要保持分開。 – jmenezes

+0

很好地工作。感謝您的幫助。 – jmenezes

相關問題