How to validate a date?

前端 未结 12 1788
被撕碎了的回忆
被撕碎了的回忆 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 04:39

    Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'? I think NOT, because the YEAR is not validated ;(

    My proposition is to use improved version of this function:

    //input in ISO format: yyyy-MM-dd
    function DatePicker_IsValidDate(input) {
            var bits = input.split('-');
            var d = new Date(bits[0], bits[1] - 1, bits[2]);
            return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
    }
    

提交回复
热议问题