我正在尝试验证使用javascript进行年龄验证的表格,但似乎无法正常工作..不知道为什么。
基本上输入了出生日期:dd/mm/yyyy
,我需要确保为了提交表格,该人的年龄在15 - 80
之间。我尝试通过这种方式进行验证,但是似乎不起作用。
HTML
<label>
Date of birth:
<input type="text" name="birth date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
JavaScript
var birthDate = document.getElementById("DOB").value;
if (2019 - birthDate < 15 || 2019 - birthDate > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
return result;
答案 0 :(得分:2)
因此,根据您的评论,您将看到一个文本框,如下所示:
<form>
<input type="text" name="birth date" id="DOB" placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}" required="required"/></label>
</form>
因此,document.getElementById("DOB").value;
的格式为dd / mm / yyyy。
因此,如果您只是检查年份,这应该可以解决问题:
onload = function() {
var form = document.getElementById("form"); //assuming this is your form's ID
form.onsubmit = validate;
}
function checkAge() {
var currentYear = new Date().getFullYear();
var birthDate = document.getElementById("DOB").value;
var errMsg = ""; //this line was missing from my code, and preventing it from working.
//turning "dd/mm/yyyy" into an array of the form { "dd", "mm", "yyyy" }, and taking the "yyyy" part
var birthYear = birthDate.split("/")[2];
var age = currentYear - birthYear;
if (age < 15 || age > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
return false; //form won't submit
}
return true; //form will submit
}
如您所见,我还使用了getFullYear()
,以便我们不对当前的固定年份进行硬编码。
但是,如果您使用<input type="date">
元素而不是文本框,可能会更清洁。
答案 1 :(得分:2)
document.getElementById("DOB").value
是字符串,而不是日期,因此您需要对其进行转换。为此,有不同的方法。一种是将字符串转换为YYYY-MM-DD格式,并将其传递给Date
构造函数。
此外,某人的年龄是在生日那天改变的,而不是在日历年的改变上改变的,因此您需要一种不同的逻辑来获取他们的年龄。一种方法是预先计算15年前和81年前的日期,并测试输入的出生日期在这两个极端之间。
var DOB = document.getElementById("DOB");
var output = document.getElementById("output");
var go = document.getElementById("go");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Function returns true when age is OK, false otherwise
function check() {
var birthDate = new Date(DOB.value.replace(/(..)\/(..)\/(....)/, "$3-$2-$1"));
return birthDate <= fifteenYearsAgo && birthDate > eightyOneYearsAgo;
}
go.addEventListener("click", function() {
if (check()) {
output.textContent = "Your age is OK";
} else {
output.textContent = "Your age must be between 15 and 80";
}
});
Birthdate: <input id="DOB"><button id="go">Go</button>
<div id="output"></div>
如果确定自己的客户端支持HTML5,则将type="date"
用作input
元素,并动态设置键入日期的min
和max
属性input
元素,并依赖于表单验证。如果表单进入了提交处理程序,则可以确定验证已通过:
var DOB = document.getElementById("DOB");
var form = document.querySelector("form");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setHours(0, 0, 0, 0);
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setHours(0, 0, 0, 0);
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Border case: in leap years next condition could be false
if ((new Date()).getDate() === eightyOneYearsAgo.getDate()) {
eightyOneYearsAgo.setDate(eightyOneYearsAgo.getDate()+1);
}
DOB.setAttribute("min", eightyOneYearsAgo.toLocaleString("se").slice(0,10));
DOB.setAttribute("max", fifteenYearsAgo.toLocaleString("se").slice(0,10));
form.addEventListener("submit", function(e) {
alert("Your age is OK");
e.preventDefault();
return false;
});
function validationMessage() {
DOB.setCustomValidity("");
const msg = DOB.checkValidity() ? ""
: DOB.validity.valueMissing ? "This field is required"
: DOB.validity.rangeOverflow ? "You must be at least 15"
: DOB.validity.rangeUnderflow ? "You must be at most 80"
: "Enter a valid date"
DOB.setCustomValidity(msg);
}
DOB.addEventListener("input", validationMessage);
validationMessage();
<form>
<label>
Date of birth:
<input type="date" name="birth date" id="DOB" required="required"/>
</label>
<button id="go">Go</button>
</form>
答案 2 :(得分:0)
document.getElementById("DOB").value;
将为您提供类似10/10/2000
的信息,并且对该字符串执行算术运算将得到NaN
。那一定是个问题。
验证日期比您想象的要复杂。您需要考虑很多事情。像时刻一样使用库来帮助您验证日期。
编辑:使用moment's Difference方法计算年龄。
答案 3 :(得分:0)
您可以使用内置的最小和最大道具进行输入。尝试这样的事情。
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="15" max="80" required>
<button onclick="myFunction()">OK</button>
<p>If the age is less than 15 or greater than 80, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
从理论上讲这应该可行。
答案 4 :(得分:0)
由于您使用的是$pdo
和pattern
,因此我假设您要以与输入日期相同的方式向用户显示错误消息(如果年龄超出范围)格式错误或丢失。这可以通过required
来实现。
如果在DOB元素上添加输入事件的事件侦听器,则可以运行一个函数来检查所输入的年龄是否已到。如果年龄超出范围或输入的日期无效,它将设置自定义错误消息。否则,它将使浏览器处理该错误(如果丢失或模式错误)。
setCustomValidity
function validateDOB(event) {
const minAge = 15, maxAge = 80;
// No custom error message. The broswer will complain if the input isn't in the
// correct form, or if the value is missing since the element has "pattern" and
// and "required".
this.setCustomValidity('');
// Check if there are any other errors
if ( !this.validity.valid ) return;
// Check format of input, and split it into parts
const dobArrayText = this.value.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
// dobArrayText is null if not in correct format. Let the broswer handle the error.
if (!dobArrayText) return;
// Decode dobArrayText to numeric values that can be used by the Date constructor.
const dob = {
year : +dobArrayText[3],
month : (+dobArrayText[2]) - 1, // month is zero based in date object.
day : +dobArrayText[1]
}
const dobDate = new Date( dob.year, dob.month, dob.day );
// Check validity of date. The date object will accept 2000-99-99 as input and
// adjust the date to 2008-07-08. To prevent that, and make sure the entered
// dobDate is a valid date, I check if the entered date is the same as the parsed date.
if (
!dobDate
|| dob.year !== dobDate.getFullYear()
|| dob.month !== dobDate.getMonth()
|| dob.day != dobDate.getDate()
) {
this.setCustomValidity('Invalid date');
return;
}
// Calc minAgeDate and maxAgeDate
const minAgeDate = new Date(dob.year + minAge, dob.month, dob.day);
const maxAgeDate = new Date(dob.year + maxAge, dob.month, dob.day);
// Get todays date and set Hours, Minutes, Seconds and Milliseconds to 0.
const todayTimestamp = new Date().setHours(0,0,0,0);
// Check validity and set a custom error message if needed.
if ( todayTimestamp < minAgeDate ) {
this.setCustomValidity(`Sorry, you must be older than ${minAge} years old`);
}
else if ( todayTimestamp >= maxAgeDate ) {
this.setCustomValidity(`Sorry, you must be younger than ${maxAge} years old`);
}
}
function formInit() {
document.getElementById('DOB').addEventListener("input", validateDOB);
}
window.addEventListener('DOMContentLoaded', formInit);