Regular Expression for MM/DD/YYYY in Javascript

后端 未结 7 1085
青春惊慌失措
青春惊慌失措 2020-12-17 20:47

I\'ve just written this regular expression in javaScript however it doesn\'t seem to work, here\'s my function:

function isGoodDate(dt){
    var reGoodDate =         


        
7条回答
  •  情深已故
    2020-12-17 21:24

    Attention, before you copy+paste: The question contains some syntactic errors in its regex. This answer is correcting the syntax. It is not claiming to be the best regex for date/time parsing.

    Try this:

    function isGoodDate(dt){
        var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
        return reGoodDate.test(dt);
    }
    

    You either declare a regular expression with:

    new RegExp("^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$")
    

    Or:

    /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/
    

    Notice the /

提交回复
热议问题