javascript日期验证未验证2月31日 [英] javascript date validation not validation February 31

查看:137
本文介绍了javascript日期验证未验证2月31日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些代码来验证表单数据。我有一个日期字段,应该有 mm / dd / yyyy 格式。我需要捕获 2月31日等异常,所以我添加了这段代码:

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

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>";
  }
}

但是我发现了一些非常奇怪的东西:而日期 02/32/2000 错误为无效日期, 02/31/2000 没有!

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

推荐答案

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

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 Date function is the same as what comes out of it, like this:

// 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;
}

然后你可以这样做:

if (isValidDate(2013,1,31))

并返回 true 如果有效, false 如果无效。

and it would return true if valid and false if invalid.

这篇关于javascript日期验证未验证2月31日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆