【问题标题】:Validating that a passed in value can be made into a date验证传入的值是否可以变成日期
【发布时间】:2013-05-22 18:18:02
【问题描述】:

我有一个文本框,假设用户输入格式为 mm/dd/yyyy 的日期。我试图确保是这种情况,并且它们不会传入字符串。由于我在下面的代码中使用 new Date() 我可以理解 startDate/endDate 是日期,即使它们是无效的......所以基本上我正在寻找进行此验证的正确方法

  function calculate() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var startDate = new Date(Date.parse(start));
    var endDate = new Date(Date.parse(end));
    var daysBetween = parseInt((endDate - startDate)/(24*3600*1000));
    var er = document.getElementById("errorResult");

    if(!(startDate instanceof Date) || !(endDate instanceof Date)) {
        er.innerHTML = "Dates must be of the form mm/dd/yyyy";
        return;
    } else if (endDate<startDate) {
        er.innerHTML = "End date must be after start date!";
        return;
    } else {
        er.innerHTML = "";
    }

【问题讨论】:

  • 这并不能直接回答您的问题,但如果您有选项,我建议您在进行大量日期操作/格式化/验证时使用 moment.js:momentjs.com/docs/#/parsing/is-valid
  • 坚持使用两位数的日期和月份很烦人,您应该接受 2013 年 4 月 5 日和 2013 年 4 月 5 日。
  • 我同意我正在计划这个,但只是问了一个一般性的问题来让我开始

标签: javascript validation types


【解决方案1】:

你可以试试这个

function isValidDate(date)
{
    var matches = /^(\d{2})[-\/\.](\d{2})[-\/\.](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[2], m = matches[1], y = matches[3];
    var newDate = new Date(y, m, d);
    return newDate.getDate() == d && newDate.getMonth() == m && newDate.getFullYear() == y;
}

在你的函数中,你可以检查

var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
if ( isValidDate( start ) && isValidDate( end ) )
{
    // valid
}

DEMO.

【讨论】:

  • 请注意,OP 使用的是美国特有的月/日/年格式,您的代码假定为日/月/年。另请注意,2013 年 5 月 4 日在两个系统中都是“有效”日期,但代表不同的日期,您可能希望包含“.”。作为分隔符。最后,要验证日期,您只需要测试任意两个值(例如日期和月份),而不是全部三个。但它不疼。 :-)
  • @RobG,非常感谢您指出日期格式和提示 :-)
【解决方案2】:

使用正则表达式

if (!inputDate.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
  er.innerHTML = "Dates must be of the form mm/dd/yyyy";
  return;
}

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多