javascript 日期验证不是验证 2 月 31 日

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21188420/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:19:13  来源:igfitidea点击:

javascript date validation not validation February 31

javascriptvalidation

提问by user1015214

I am trying to write some code with will validate form data. I have a date field which should have a mm/dd/yyyyformat. I needed to catch exceptions such as February 31, so I added this code:

我正在尝试编写一些代码来验证表单数据。我有一个应该有mm/dd/yyyy格式的日期字段。我需要捕获诸如February 31 之类的异常,因此我添加了以下代码:

var d = new Date(dob);
if (isNaN(d.getTime())) { //this if is to take care of February 31, BUT IT DOESN'T!
  error = 1;
  message += "<li>Invalid Date</li>";
} else {
  var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
  var validFormat = date_regex.test(dob);
  if (!(validFormat)) {
    error = 1;
    message += "<li>Invalid date format - date must have format mm/dd/yyyy</li>";
  }
}

However I found something very weird: while the date 02/32/2000errors as an invalid date, 02/31/2000does not!

但是我发现了一些非常奇怪的事情:虽然日期02/32/2000错误是无效日期,但02/31/2000却不是!

回答by Jeff Shaver

Due to what I said in the comments...

由于我在评论中所说的......

Another way you could check if a date is valid is by checking whether or not the stuff you passed into the new Datefunction is the same as what comes out of it, like this:

您可以检查日期是否有效的另一种方法是检查您传递给new Date函数的内容是否与它的内容相同,如下所示:

// Remember that the month is 0-based so February is actually 1...
function isValidDate(year, month, day) {
    var d = new Date(year, month, day);
    if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
        return true;
    }
    return false;
}

then you could do this:

那么你可以这样做:

if (isValidDate(2013,1,31))

and it would return trueif valid and falseif invalid.

true如果有效和false无效,它将返回。

回答by Reuel Ribeiro

After wrecking my head with the obscurity of Date.getMonth()(and also weekday by .getDay()) being 0-index(despite year, day and all the others not being like so... oh god...) I've re-wrote Jeff's answer to make it more readable and more friendly-usable to whom consume the method from outside.

在被Date.getMonth()(以及工作日.getDay()0-index(尽管年,日和所有其他人都不是这样......天啊......)并且对从外部使用该方法的人更加友好。

ES6 code

ES6代码

You can call passing month as 1-indexedas you'd normally expect.

您可以1-indexed像通常期望的那样调用过去的月份。

I've parsed inputs using Number constructorso I can use strict equalityto more confidently compare values.

我已经使用Number 构造函数解析了输入,因此我可以使用严格相等来更自信地比较值。

I'm using the UTCversion methods to avoid having to deal with the local timezone.

我正在使用UTC版本方法来避免处理本地时区。

Also, I broke steps down into some variables for the sake of readability.

此外,为了可读性,我将步骤分解为一些变量。

/**
 *
 * @param { number | string } day
 * @param { number | string } month
 * @param { number| string } year
 * @returns { boolean }
 */
function validateDateString(day, month, year) {

    day = Number(day);
    month = Number(month) - 1; //bloody 0-indexed month
    year = Number(year);

    let d = new Date(year, month, day);

    let yearMatches = d.getUTCFullYear() === year;
    let monthMatches = d.getUTCMonth() === month;
    let dayMatches = d.getUTCDate() === day;

    return yearMatches && monthMatches && dayMatches;
}

回答by Stephen

Are you able to use a library?

你可以使用图书馆吗?

My first port of call for date handling in Javascript is moment.js: "A javascript date library for parsing, validating, manipulating, and formatting dates."

我在 Javascript 中处理日期的第一个端口是moment.js:“一个用于解析、验证、操作和格式化日期的 javascript 日期库。”

回答by kennebec

The ususal way to validate a 'mm/dd/yyyy' date string is to create a date object and verify that its month and date are the same as the input.

验证“mm/dd/yyyy”日期字符串的常用方法是创建一个日期对象并验证其月份和日期是否与输入相同。

function isvalid_mdy(s){
    var day, A= s.match(/[1-9][\d]*/g);
    try{
        A[0]-= 1;
        day= new Date(+A[2], A[0], +A[1]);
        if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
        throw new Error('Bad Date ');
    }
    catch(er){
        return er.message;
    }
}

isvalid_mdy('02/31/2000')

isvalid_mdy('02/31/2000')

/* returned value: (Error)Bad Date */

/* 返回值:(错误)错误日期 */