如何在JavaScript中使用格式"mm/dd/yyyy"验证日期?

mat*_*att 88 javascript validation date

我想使用格式验证输入的日期格式mm/dd/yyyy.

我在一个站点中找到了以下代码然后使用它但它不起作用:

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!'); 
    } 
}
Run Code Online (Sandbox Code Playgroud)

关于什么可能是错的任何建议?

Eli*_*ing 173

我认为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];
};
Run Code Online (Sandbox Code Playgroud)

  • 记得使用parseInt的第二个参数:`parseInt(parts [0],10)`.否则,九月的'09`被读作八进制并解析为0 (9认同)
  • 我建议你把正则表达式更改为:/ ^(\ d {2} |\d {1})\ /(\ d {2} |\d {1})\ /\d {4} $/this方式它捕获一个月的数字和日期1/5/2014.谢谢你的样品! (4认同)

Raz*_*aul 102

我会使用Moment.js进行日期验证.

alert(moment("05/22/2012", 'MM/DD/YYYY',true).isValid()); //true
Run Code Online (Sandbox Code Playgroud)

Jsfiddle:http://jsfiddle.net/q8y9nbu5/

  • +1我绝对不得不将其作为所有提交者中唯一非常正确的答案!你不想做一些像你自己的日期解析一样复杂的事情! (19认同)
  • 使用"M/D/YYYY"允许月份和日期为1-2位数. (5认同)
  • 很高兴知道第三个参数“ true”保留为“使用严格解析” https://momentjs.com/docs/#/parsing/string-format/ (2认同)

Rav*_*ant 38

使用以下正则表达式来验证:

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;
}
Run Code Online (Sandbox Code Playgroud)

这对MM/dd/yyyy来说很有用.

  • 您可以使用/ ^ [0-9] {4} - (0 [1-9] | 1 [0-2]) - (0 [1-9] | [1-2] [0-9] | 3 [0-1])$ ​​/验证yyyy-mm-dd. (6认同)
  • 3000年会发生什么?:) (4认同)
  • @ TheOne..y3k问题..:P (4认同)
  • 我们如何验证**yyyy-mm-dd**或无效日期,如**9834-66-43** (3认同)
  • 这太棒了,因为我讨厌制定正则表达式和两个喜欢它们的效率! (2认同)
  • 闰年和月份的变化怎么样? (2认同)
  • 二月怎么样?日期 30? (2认同)

Mat*_*ija 26

所有学分都归于elian-ebbing

对于这里的懒人我也提供了格式为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];
}
Run Code Online (Sandbox Code Playgroud)


Jay*_*ing 13

看到一篇关于这样一个基本主题的帖子这么老,有这么多答案,但没有一个是正确的,这是不寻常的。(我并不是说它们都不起作用。)

  • 为此不需要闰年确定程序。语言可以为我们完成这项工作。
  • 这不需要片刻。
  • Date.parse()不应用于本地日期字符串。MDN说“不建议使用 Date.parse,因为直到 ES5,字符串的解析完全依赖于实现。” 该标准需要(可能是简化的)ISO 8601 字符串;对任何其他格式的支持取决于实现。
  • 也不应该new Date(string)使用,因为它使用 Date.parse()。
  • IMO 应验证闰日。
  • 验证函数必须考虑输入字符串与预期格式不匹配的可能性。例如,“1a/2a/3aaa”、“1234567890”或“ab/cd/efgh”。

这是一个没有隐式转换的高效、简洁的解决方案。它利用了 Date 构造函数将 2018-14-29 解释为 2019-03-01 的意愿。它确实使用了一些现代语言功能,但如果需要,可以轻松删除这些功能。我还包括了一些测试。

function isValidDate(s) {
    // Assumes s is "mm/dd/yyyy"
    if ( ! /^\d\d\/\d\d\/\d\d\d\d$/.test(s) ) {
        return false;
    }
    const parts = s.split('/').map((p) => parseInt(p, 10));
    parts[0] -= 1;
    const d = new Date(parts[2], parts[0], parts[1]);
    return d.getMonth() === parts[0] && d.getDate() === parts[1] && d.getFullYear() === parts[2];
}

function testValidDate(s) {
    console.log(s, isValidDate(s));
}
testValidDate('01/01/2020'); // true
testValidDate('02/29/2020'); // true
testValidDate('02/29/2000'); // true
testValidDate('02/29/1900'); // false
testValidDate('02/29/2019'); // false
testValidDate('01/32/1970'); // false
testValidDate('13/01/1970'); // false
testValidDate('14/29/2018'); // false
testValidDate('1a/2b/3ccc'); // false
testValidDate('1234567890'); // false
testValidDate('aa/bb/cccc'); // false
testValidDate(null);         // false
testValidDate('');           // false
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案。可以使用 `const [mm, dd, yyyy] = date.split('/').map((p) =&gt; parseInt(p));` 而不是 `parts[x]` 来提高可读性 (2认同)

use*_*274 12

你可以用 Date.parse()

您可以阅读MDN文档

Date.parse()方法解析日期的字符串表示形式,并返回自1970年1月1日00:00:00 UTC或NaN后的毫秒数(如果字符串无法识别,或者在某些情况下包含非法日期值) (例如2015-02-31).

并检查Date.parseisNaN 的结果

let isValidDate = Date.parse('01/29/1980');

if (isNaN(isValidDate)) {
  // when is not valid date logic

  return false;
}

// when is valid date logic
Run Code Online (Sandbox Code Playgroud)

请查看建议Date.parse在MDN中使用的时间

  • Date.parse 会给你一个有效的解析,日期如“46/7/17” (2认同)
  • 被否决,因为这会让垃圾通过。例如 `Date.parse('01//////29//000')` (2认同)

Nik*_*las 10

它似乎适用于mm/dd/yyyy格式日期,例如:

http://jsfiddle.net/niklasvh/xfrLm/

我对你的代码唯一的问题是:

var ExpiryDate = document.getElementById(' ExpiryDate').value;
Run Code Online (Sandbox Code Playgroud)

括号内有一个空格,在元素ID之前.将其更改为:

var ExpiryDate = document.getElementById('ExpiryDate').value;
Run Code Online (Sandbox Code Playgroud)

如果没有关于不起作用的数据类型的任何进一步细节,则没有太多可以提供输入的内容.


gan*_*esh 9

如果给定的字符串格式正确('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'));
            
Run Code Online (Sandbox Code Playgroud)