Regular Expression for MM/DD/YYYY in Javascript

后端 未结 7 1075
青春惊慌失措
青春惊慌失措 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:26

    I agree with @KooiInc, but it is not enough to test for NaN

    function isGoodDate(dt){
        var dts  = dt.split('/').reverse()
           ,dateTest = new Date(dts.join('/'));
        return !isNaN(dateTest) && 
           dateTest.getFullYear()===parseInt(dts[0],10) &&
           dateTest.getMonth()===(parseInt(dts[1],10)-1) &&
           dateTest.getDate()===parseInt(dts[2],10) 
    }
    

    which will handle 29/2/2001 and 31/4/2011


    For this script to handle US dates do

    function isGoodDate(dt){
        var dts  = dt.split('/')
           ,dateTest = new Date(dt);
        return !isNaN(dateTest) && 
           dateTest.getFullYear()===parseInt(dts[2],10) &&
           dateTest.getMonth()===(parseInt(dts[0],10)-1) &&
           dateTest.getDate()===parseInt(dts[1],10) 
    }
    

提交回复
热议问题