Best way to validate date string format via jQuery

前端 未结 2 1723
星月不相逢
星月不相逢 2020-11-30 15:39

I found a lot of links to validate string if it is a date.

Like here and here.

But anyway I cannot figure out how to validate if we have this thing:

2条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 15:47

    Use a regular expression.

    var dateRegEx = /^(0[1-9]|1[012]|[1-9])[- /.](0[1-9]|[12][0-9]|3[01]|[1-9])[- /.](19|20)\d\d$/
    
    console.log("06/06/2012".match(dateRegEx) !== null) // true
    console.log("6/6/2012".match(dateRegEx) !== null) // true
    console.log("6/30/2012".match(dateRegEx) !== null) // true
    console.log("30/06/2012".match(dateRegEx) !== null) // false
    

    Learn about RegEx.

    Edit - A Disclaimer

    As @elclanrs pointed out, this only validates the string's format, and not the actual date, which means that dates like February 31st would pass. However, since the OP only asks "to validate date string format," I'll keep this answer here because for some, it might be all you need.

    As a note, the jQuery Validation plugin that the OP was using, also only validates format.

    Finally, for those wondering, if you needed to validate the date, and not just the format, this regular expression would have ~2% rate of failure over the domain of (1-12)/(1-31)/(1900-2099) date strings. Please don't use this in Mission Critical code for JPL.

提交回复
热议问题