How to validate a date?

前端 未结 12 1794
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 04:13

I\'m trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.

How can I do this with any date?

12条回答
  •  温柔的废话
    2020-11-22 05:02

    It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):

    const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
    function isValidDate(strDate) {
      if (!dateValidationRegex.test(strDate)) return false;
      const [m, d, y] = strDate.split('/').map(n => parseInt(n));
      return m === new Date(y, m - 1, d).getMonth() + 1;
    }
    
    ['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
      console.log(d, isValidDate(d));
    });

提交回复
热议问题