How to validate a date?

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

    This is ES6 (with let declaration).

    function checkExistingDate(year, month, day){ // year, month and day should be numbers
         // months are intended from 1 to 12
        let months31 = [1,3,5,7,8,10,12]; // months with 31 days
        let months30 = [4,6,9,11]; // months with 30 days
        let months28 = [2]; // the only month with 28 days (29 if year isLeap)
    
        let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
    
        let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
    
        return valid; // it returns true or false
    }
    

    In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:

    let months31 = [0,2,4,6,7,9,11];
    let months30 = [3,5,8,10];
    let months28 = [1];
    

    If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:

    let arrayWithDayMonthYear = myDateInString.split('/');
    let year = parseInt(arrayWithDayMonthYear[2]);
    let month  = parseInt(arrayWithDayMonthYear[1]);
    let day = parseInt(arrayWithDayMonthYear[0]);
    

提交回复
热议问题