如何在 JavaScript 中以“mm/dd/yyyy”格式验证日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6177975/
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
How to validate date with format "mm/dd/yyyy" in JavaScript?
提问by matt
I want to validate the date formaton an input using the format mm/dd/yyyy
.
我想使用 format验证输入上的日期格式mm/dd/yyyy
。
I found below codes in one site and then used it but it doesn't work:
我在一个站点中找到以下代码,然后使用它,但它不起作用:
function isDate(ExpiryDate) {
var objDate, // date object initialized from the ExpiryDate string
mSeconds, // ExpiryDate in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (ExpiryDate.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0
day = ExpiryDate.substring(3, 5) - 0;
year = ExpiryDate.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert ExpiryDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
function checkDate(){
// define date string to test
var ExpiryDate = document.getElementById(' ExpiryDate').value;
// check date and print message
if (isDate(ExpiryDate)) {
alert('OK');
}
else {
alert('Invalid date format!');
}
}
Any suggestion about what could be wrong?
关于可能出什么问题的任何建议?
回答by Elian Ebbing
I think Niklas has the right answer to your problem. Besides that, I think the following date validation function is a little bit easier to read:
我认为 Niklas 对您的问题有正确的答案。除此之外,我认为以下日期验证函数更容易阅读:
// Validates that the input string is a valid date formatted as "mm/dd/yyyy"
function isValidDate(dateString)
{
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
};
回答by Razan Paul
I would use Moment.jsfor date validation.
我会使用Moment.js进行日期验证。
alert(moment("05/22/2012", 'MM/DD/YYYY',true).isValid()); //true
Jsfiddle: http://jsfiddle.net/q8y9nbu5/
jsfiddle:http: //jsfiddle.net/q8y9nbu5/
true
value is for strict parsingcredit to @Andrey Prokhorov which means
true
值用于严格解析@Andrey Prokhorov,这意味着
you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.
您可以为最后一个参数指定一个布尔值,以使 Moment 使用严格解析。严格解析要求格式和输入完全匹配,包括分隔符。
回答by Ravi Kant
Use the following regular expression to validate:
使用以下正则表达式进行验证:
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(testDate))) {
return false;
}
This is working for me for MM/dd/yyyy.
这对我来说适用于 MM/dd/yyyy。
回答by Matija
All credits go to elian-ebbing
Just for the lazy ones here I also provide a customized version of the function for the format yyyy-mm-dd.
对于这里的懒人,我还提供了一个自定义版本的函数,格式为yyyy-mm-dd。
function isValidDate(dateString)
{
// First check for the pattern
var regex_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;
if(!regex_date.test(dateString))
{
return false;
}
// Parse the date parts to integers
var parts = dateString.split("-");
var day = parseInt(parts[2], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[0], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
{
return false;
}
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
{
monthLength[1] = 29;
}
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}
回答by user615274
You could use Date.parse()
你可以用 Date.parse()
You can read in MDN documentation
您可以在MDN 文档中阅读
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Date.parse() 方法解析日期的字符串表示,并返回自 1970 年 1 月 1 日 00:00:00 UTC 或 NaN 以来的毫秒数(如果字符串无法识别,或者在某些情况下包含非法日期值) (例如 2015-02-31)。
And check if the result of Date.parse
isNaN
并检查Date.parse
isNaN的结果是否
let isValidDate = Date.parse('01/29/1980');
if (isNaN(isValidDate)) {
// when is not valid date logic
return false;
}
// when is valid date logic
Please take a look when is recommended to use Date.parse
in MDN
请看一下什么时候推荐Date.parse
在MDN中使用
回答by Niklas
It appears to be working fine for mm/dd/yyyy format dates, example:
它似乎适用于 mm/dd/yyyy 格式的日期,例如:
http://jsfiddle.net/niklasvh/xfrLm/
http://jsfiddle.net/niklasvh/xfrLm/
The only problem I had with your code was the fact that:
我对您的代码的唯一问题是:
var ExpiryDate = document.getElementById(' ExpiryDate').value;
Had a space inside the brackets, before the element ID. Changed it to:
在元素 ID 之前的方括号内有一个空格。改为:
var ExpiryDate = document.getElementById('ExpiryDate').value;
Without any further details regarding the type of data that isn't working, there isn't much else to give input on.
如果没有关于不起作用的数据类型的任何进一步详细信息,就没有什么可以提供输入的了。
回答by ganesh
The function will return true if the given string is in the right format('MM/DD/YYYY') else it will return false. (I found this code online & modified it a little)
如果给定的字符串格式正确('MM/DD/YYYY'),则该函数将返回 true,否则将返回 false。(我在网上找到了这段代码并稍作修改)
function isValidDate(date) {
var temp = date.split('/');
var d = new Date(temp[2] + '/' + temp[0] + '/' + temp[1]);
return (d && (d.getMonth() + 1) == temp[0] && d.getDate() == Number(temp[1]) && d.getFullYear() == Number(temp[2]));
}
console.log(isValidDate('02/28/2015'));
回答by Daniel Tran
Here is one snippet to check for valid date:
这是检查有效日期的一个片段:
function validateDate(dateStr) {
const regExp = /^(\d\d?)\/(\d\d?)\/(\d{4})$/;
let matches = dateStr.match(regExp);
let isValid = matches;
let maxDate = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (matches) {
const month = parseInt(matches[1]);
const date = parseInt(matches[2]);
const year = parseInt(matches[3]);
isValid = month <= 12 && month > 0;
isValid &= date <= maxDate[month] && date > 0;
const leapYear = (year % 400 == 0)
|| (year % 4 == 0 && year % 100 != 0);
isValid &= month != 2 || leapYear || date <= 28;
}
return isValid
}
console.log(['1/1/2017', '01/1/2017', '1/01/2017', '01/01/2017', '13/12/2017', '13/13/2017', '12/35/2017'].map(validateDate));
回答by rung
It's ok if you want to check validate dd/MM/yyyy
如果你想检查validate dd/MM/yyyy也可以
function isValidDate(date) {
var temp = date.split('/');
var d = new Date(temp[1] + '/' + temp[0] + '/' + temp[2]);
return (d && (d.getMonth() + 1) == temp[1] && d.getDate() == Number(temp[0]) && d.getFullYear() == Number(temp[2]));
}
alert(isValidDate('29/02/2015')); // it not exist ---> false
回答by Dinesh Lomte
Find in the below code which enables to perform the date validation for any of the supplied format to validate start/from and end/to dates. There could be some better approaches but have come up with this. Note supplied date format and date string go hand in hand.
在下面的代码中查找可以对任何提供的格式执行日期验证,以验证开始/从和结束/到日期。可能有一些更好的方法,但已经提出了这个。注意提供的日期格式和日期字符串是相辅相成的。
<script type="text/javascript">
function validate() {
var format = 'yyyy-MM-dd';
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
</script>
Below is the HTML snippet
下面是 HTML 片段
<input type="text" name="start" id="start" size="10" value="" />
<br/>
<input type="text" name="end" id="end" size="10" value="" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate();" />