jQuery.validation 在生日年龄验证中添加方法错误
jQuery.validation add Method error on birthday age validation
我正在使用jQuery.validation gem,当年龄超过18岁时,我在控制台中出现了未知的代码部分。您可以提交表单,但输入正确的值后,错误消息不会动态消失。我认为这是我的消息显示方式的一个直接错误,但我无法弄清楚。
控制台亮点
- 来自 jQuery 验证插件 v1.13.1 "result = $.validator.methods[ method ].call( this, val, element, 规则参数);"
配置文件.js
$(document).ready(function () {
{{$('#new_profile').validate({
rules: {
'profile[first_name]': {
required: true,
minlength: 2
},
'profile[last_name]': {
required: true,
minlength: 2
},
'profile[location]': {
required: true,
minlength: 2
},
'profile[birthday]': {
check_date_of_birth: true,
require: true
},
'profile[operating_system]': {
minlength: 1
},
'profile[about_me]': {
required: true,
minlength: 5,
maxlength: 500
}
}
})
});
$.validator.addMethod("check_date_of_birth", function(value, element) {
var birthday = $("#profile_birthday").val();
var birthdaydate = Date.parse(birthday);
var difference = Date.now() - birthdaydate;
var ageYear = new Date(difference);
var age = Math.abs(ageYear.getUTCFullYear() - 1970);
return age > 18;
}, "You must be at least 18 years of age.");
profile_form
<div class="form_input">
<%= f.label(:birthday, "Date of Birth:") %>
<%= f.date_field(:birthday) %>
<label id="errorBirthday"></label>
我们需要扩展插件以创建自定义验证方法,以使用出生数据检查最低年龄:
<input type="date" name="dob" placeholder="mm/dd/yyyy"/>
$(document).ready(function() {
$.validator.addMethod("minAge", function(value, element, min) {
var today = new Date();
var birthDate = new Date(value);
var age = today.getFullYear() - birthDate.getFullYear();
if (age > min + 1) {
return true;
}
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age >= min;
}, "You are not old enough!");
$("form").validate({
rules: {
dob: {
required: true,
minAge: 18
}
},
messages: {
dob: {
required: "Please enter you date of birth.",
minAge: "You must be at least 18 years old!"
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<form>
<input type="date" name="dob" placeholder="mm/dd/yyyy" />
<br><br>
<input type="submit" value="Submit">
</form>
亚塔万的回答是救命稻草。我只有一个小的调整,让它仍然将其标记为无效日期,以防适当的年龄或太年轻之间只有 1 天的差距:
(在比较当前日期和出生日期时添加了" <= "),如下所示:
if (m < 0 || (m === 0 && today.getDate() <= birthDate.getDate())) {
age--;
}
相关文章:
- 在对象中添加方法时出现问题
- 什么意思是“;向原型添加方法”;
- jQuery验证器添加方法未定义
- 向通过ReST JSON调用生成的Angular Javascript对象添加方法
- 向React中的高阶组件添加方法
- 向JavaScript对象添加方法
- 如何向[]添加方法
- 如何在流星js中为对象添加方法
- jQuery.validation 在生日年龄验证中添加方法错误
- 使用 IE8 添加方法的 JavaScript 错误
- 向方法添加方法
- 如何在 Javascript ES6 中向类添加方法
- Javascript:向对象类添加方法的优缺点是什么
- 如何更改“动物”的原型并添加方法“sayName”来打印语句
- 如何在 Illustrator CS5.1+ 中创建画板对象的添加方法所需的矩形对象
- 如何在 nodejs 中全局添加方法到 JSON、Date 或其他“本机”对象
- 什么类/类型是未定义的,是否可以向其扩展/添加方法
- 为什么在 javascript 中向数组原型添加方法会破坏 for 循环上的迭代
- 向对象添加方法
- 动态添加方法到对象