2011-11-21 139 views
0

我正在使用jQuery驗證插件來驗證我的網站的註冊表單。用戶必須做的一件事是輸入他們的生日,他們必須是18才能使用該網站。我通過三個下拉菜單輸入生日。我想驗證這個條目(以確保他們做到了,以確保他們有至少18個,但我不理解定製檢驗的建築物下面是我在表單代碼:Jquery下拉日期驗證

<p> 
      <label for="user_birthday">Birthday</label> 
      <br> 
      <select id="user_birthday_2i" name="user[birthday(2i)]"> 
      <option value="1">January</option> 
      <option value="2">February</option> 
      <option value="3">March</option> 
      etc.... 
      </select> 
      <select id="user_birthday_3i" name="user[birthday(3i)]"> 
      <option value="1">1</option> 
      <option value="2">2</option> 
      <option value="3">3</option> 
      etc... 
      </select> 
      <select id="user_birthday_1i" name="user[birthday(1i)]"> 
      <option value="2010">2010</option> 
      <option value="2011">2011</option> 
      etc... 
      </select> 
      </p> 

有誰建這樣的驗證使用jQuery驗證插件之前?

回答

2

我正在使用jQuery Validation Plugin,這是工作克,所以我想堅持下去。基本上我不得不添加一個自定義驗證器,並最終使用date.js庫來解釋日期。像這樣:

# formats the date into a hidden field that can be validated when the dropdowns are changed. 
$('#user_birthday_3i,#user_birthday_2i,#user_birthday_1i').change(function() { 
     $('#user_birthday').val($('#user_birthday_3i').val()+'/'+ $('#user_birthday_2i').val()+'/'+ $('#user_birthday_1i').val()); 
    }); 


# uses date.js to interpret the date and do a little math 
jQuery.validator.addMethod("ofAge", function(value, element) { 
     return Date.parse($("#user_birthday").val()) < (18).years().ago(); 
    }, "You must be 18 years old to join."); 


# validated the form using the jquery validation plugin 
$("#new_user_signup").validate({ 
    rules: { 
     "user[birthday]": { 
      required: true, 
      date: true, 
      ofAge: true 
     } 
    }, 
    messages: { 
     "user[birthday]": { 
      required: "Please enter your birthday.", 
      date: "Please enter your birthday." 
     } 
    } 
}); 

不知道這是否是最好的方法,總的來說,但它對我有用!

1

人們通常知道他們的生日非常好,所以我寧願讓他們鍵入它。驗證的日期是很容易的事。

Birthday:<input name="birthday" onblur="validate18(this);"> 
<br> 
<span class="hint">day/month/year</span> 
<br> 
<span id="birthdayError" class="errorMessage"></span> 

<script> 

function validate18(el) { 
    var bits = typeof el.value == 'string'? el.value.split('/') : []; 
    var d = new Date(bits[2], bits[1]-1, bits[0]); 
    var err = document.getElementById(el.name + 'Error'); 

    // Check date was valid 
    if (d && d.getFullYear() == bits[2] && d.getMonth() == bits[1]-1) { 

     // Check is 18 years ago or more 
     var testDate = new Date(); 
     var testDate = testDate.setYear(testDate.getFullYear() - 18); 
     err.innerHTML = (testDate - d < 0)? 'Sorry, you aren\'t 18 yet' : ''; 
    } else { 
     err.innerHTML = 'Please enter a valid date'; 
    } 
} 

</script> 
+0

這很好。你有什麼特別的理由讓你通過下拉式輸入嗎?我只是不想遇到用戶輸入3-3-85而不是3/3/85或者來自不同國家的人等的問題。似乎對用戶來說更多的工作。 – goddamnyouryan

+1

你可以在分割中使用正則表達式來分割任何你喜歡的東西,甚至是/ \ D /所以任何非數字字符。我更喜歡在日期選擇器很煩人的時候輸入它,只是對用戶做最好的選擇。 – RobG