2009-07-31 73 views
1

消息我有這個條件在我的驗證:如何顯示在有條件的jQuery驗證插件

consent: { 
    required: function(element) { 
     var age = getAge($("#birthdate").val()); 
     if(age >= 18){ 
      return false; 
     } else if(age >= 13 && age <=17){ 
      $('#consent:checked'); 
     } else { 
      //should show error message not ligible to register 
     } 
    } 
} 

如何從上述條件返回的消息?

+0

http://stackoverflow.com/questions/1212293/please-helpi-i-不能得到我的代碼工作的jQuery的驗證 – Macros 2009-07-31 12:48:59

回答

4

我會創建一個特殊的規則與每個條件與關聯的消息。對於年齡,它必須大於13.對於同意,它是必需的,但僅當年齡小於18時。

$.validator.addMethod('minimumAge', function(value,element) { 
    return getAge(element) >= value; 
}); 
$('form').validate({ 
     rules: { 
      age: minimumAge(13), 
      consent: { 
       required: function(element) { 
           return getAge($('#birthDate') < 18; 
         } 
      } 
     } 
     messages: { 
      age: "You must be older than 13 to register.", 
      consent: "If you are under 18 your must have your parent's consent to register." 
     } 
}); 
+1

感謝您的答案,但處理年齡的字段是一個文本框,用戶輸入他們的出生日期。所以用戶沒有進入他們的年齡,我有getAge函數來計算他們的年齡。 – christian 2009-07-31 11:04:28