[英]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, rule.parameters );”
配置文件.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.");
個人資料表格
<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>
yathavan 的答案是救命稻草。 我只做了一個小調整,使它仍然會標記它為無效日期,以防適當的年齡或太年輕之間只有 1 天的差異:
(當日與出生日比較時加一個'<='),如下:
if (m < 0 || (m === 0 && today.getDate() <= birthDate.getDate())) {
age--;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.