2011-11-21 250 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