我正在使用jQuery Validation插件验证我的网站的注册表单。用户必须做的事情之一是输入他们的生日,他们必须是18才能使用该网站。我通过三个下拉菜单输入了生日。我想验证这个条目(以确保他们这样做并确保它们至少为18,但我无法理解自定义验证器的构建。这是我的代码形式:
<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 Validation插件之前,有没有人构建过这样的验证器?
答案 0 :(得分: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 :(得分: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>