Html Javascript 日期验证 (DD/MM/YYYY) 和年龄检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19820257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Date Validation ( DD/MM/YYYY) & Age Checking
提问by A. Mesut Konuklar
I've started to work on Javascript recently. What I am testing is checking the DoB in valid format. Next step will be checking the age.
我最近开始研究 Javascript。我正在测试的是检查有效格式的 DoB。下一步将检查年龄。
What my HTML code includes is below
我的 HTML 代码包含的内容如下
<form name="ProcessInfo" action="#" method="POST" enctype="multipart/form-data" target="_self" onsubmit="return checkForm();">
.
.
.
.
<br>
<label for="txtDOB">Date of Birth:* </label>
<input id="txtDOB" type="text" name="txtDOB" size="12">
format: ##/##/####
<br>
.
.
.
</form>
.
.
and I did the following in my .js file
我在我的 .js 文件中做了以下事情
var errMessage = "";
function checkForm() {
validateName();
validateSurname();
carSelect();
validateDOB();
if (errMessage == "") {
} else {
alert(errMessage);
}
}
...
function validateDOB()
{
var dob = document.forms["ProcessInfo"]["txtDOB"].value;
var pattern = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
if (dob == null || dob == "" || !pattern.test(dob)) {
errMessage += "Invalid date of birth\n";
return false;
}
else {
return true
}
}
I tried to check if its valid with regular expression but I always get an alert even if I type the date correctly. And how can I seperate the DD / MM / YYYY to calculate the age?
我试图用正则表达式检查它是否有效,但即使我正确输入了日期,我也总是收到警报。我怎样才能分开 DD / MM / YYYY 来计算年龄?
回答by Drahcir
If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:
如果要在格式中使用正斜杠,则需要在正则表达式中使用反斜杠进行转义:
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
回答by Brigand
I suggest using moment.jswhich provides an easy to use method for doing this.
我建议使用moment.js,它提供了一种易于使用的方法来执行此操作。
interactive demo
互动演示
function validate(date){
var eighteenYearsAgo = moment().subtract(18, "years");
var birthday = moment(date);
if (!birthday.isValid()) {
return "invalid date";
}
else if (eighteenYearsAgo.isAfter(birthday)) {
return "okay, you're good";
}
else {
return "sorry, no";
}
}
To include moment in your page, you can use CDNJS:
要在页面中包含 moment,您可以使用 CDNJS:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>
回答by Lim H.
I'd utilize the built in Date
object to do the validation for me. Even after you switch from -
to /
you still need to check whether the month is between 0 and 12, the date is between 0 and 31 and the year between 1900 and 2013 for example.
我会利用内置Date
对象为我进行验证。即使你从 切换-
到/
你仍然需要检查月份是否在 0 和 12 之间,日期是否在 0 和 31 之间,以及 1900 和 2013 之间的年份。
function validateDOB(){
var dob = document.forms["ProcessInfo"]["txtDOB"].value;
var data = dob.split("/");
// using ISO 8601 Date String
if (isNaN(Date.parse(data[2] + "-" + data[1] + "-" + data[0]))) {
return false;
}
return true;
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Example:_Using_parsefor more information.
回答by user1089766
If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:
如果要在格式中使用正斜杠,则需要在正则表达式中使用反斜杠进行转义:
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
回答by Mayur Narula
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function dateCheck() {
debugger;
var inputValues = document.getElementById('dateInput').value + ' ' + document.getElementById('monthInput').value + ' ' + document.getElementById('yearInput').value;
var d = new Date();
var n = d.getHours();
var m = d.getMinutes();
var p = d.getSeconds();
var date = document.getElementById("dateInput").value;
var month = document.getElementById("monthInput").value;
var year = document.getElementById("yearInput").value;
var dateCheck = /^(0?[1-9]|[12][0-9]|3[01])$/;
var monthCheck = /^(0[1-9]|1[0-2])$/;
var yearCheck = /^\d{4}$/;
if (month.match(monthCheck) && date.match(dateCheck) && year.match(yearCheck)) {
var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month == 1 || month > 2) {
if (date > ListofDays[month - 1]) {
alert('Invalid date format!');
return false;
}
}
if (month == 2) {
var leapYear = false;
if ((!(year % 4) && year % 100) || !(year % 400)) {
leapYear = true;
}
if ((leapYear == false) && (date >= 29)) {
alert('Invalid date format!');
return false;
}
if ((leapYear == true) && (date > 29)) {
alert('Invalid date format!');
return false;
}
}
var flag = 1
}
else {
alert("invalid date");
}
if (flag == 1) {
alert("the date is:" + inputValues + " " + "The time is:" + n + ":" + m + ":" + p);
}
clear();
}
function clear() {
document.myForm.dateInput.value = "";
document.myForm.monthInput.value = "";
document.myForm.yearInput.value = "";
}
</script>
</head>
<body>
<div>
<form name="myForm" action="#">
<table>
<tr>
<td>Enter Date</td>
<td><input type='text' name='dateInput' id="dateInput" placeholder="Date" maxlength="2" onclick="dateCheck(document.myForm.dateInput)" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"/></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<td>Enter Month</td>
<td><input type='text' name='monthInput' id="monthInput" placeholder="Month" maxlength="2" onclick="dateCheck(document.myForm.dateInput)" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"/></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<td>Enter Year</td>
<td><input type='text' name='yearInput' id="yearInput" placeholder="Year" minlength="4" maxlength="4" onclick="dateCheck()" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"/></td>
<td><span id="span3"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" onclick="dateCheck()"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<td>
回答by abhiklpm
You have used regular expression for this format : DD - MM- YYYY
您已为此格式使用了正则表达式:DD - MM- YYYY
If you need this format DD/MM/YYYY use
如果您需要这种格式 DD/MM/YYYY 使用
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
回答by Rune Jeppesen
It is two problems - is the slashes the right places and is it a valid date. I would suggest you catch input changes and put the slashes in yourself. (annoying for the user)
这是两个问题 - 斜线的位置是否正确以及它是否是有效日期。我建议您捕获输入更改并自己添加斜杠。(对用户来说很烦人)
The interesting problem is whether they put in a valid date and I would suggest exploiting how flexible js is:
有趣的问题是他们是否输入了有效的日期,我建议利用 js 的灵活性:
function isValidDate(str) {
var newdate = new Date();
var yyyy = 2000 + Number(str.substr(4, 2));
var mm = Number(str.substr(2, 2)) - 1;
var dd = Number(str.substr(0, 2));
newdate.setFullYear(yyyy);
newdate.setMonth(mm);
newdate.setDate(dd);
return dd == newdate.getDate() && mm == newdate.getMonth() && yyyy == newdate.getFullYear();
}
console.log(isValidDate('jk'));//false
console.log(isValidDate('290215'));//false
console.log(isValidDate('290216'));//true
console.log(isValidDate('292216'));//false
回答by rung
Using pattern and check validate:
使用模式并检查验证:
var input = '33/15/2000';
var pattern = /^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/;
alert(pattern.test(input));
回答by vikas Madaan
You can use attributes of html tag instead of validation from html input type ="date" can be used instead of validating it. That's the benifits html 5 gives you
您可以使用 html 标签的属性而不是来自 html 输入类型的验证 ="date" 可以用来代替验证它。这就是 html 5 给你的好处
回答by Kuldeep Saxena
If you're using moment
then that's the single line code:
如果您使用moment
的是单行代码:
moment(date).format("DD/MM/YYYY").isValid()
moment(date).format("DD/MM/YYYY").isValid()