How to validate a date?

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

    My function returns true if is a valid date otherwise returns false :D

    function isDate  (day, month, year){
    	if(day == 0 ){
    		return false;
    	}
    	switch(month){
    		case 1: case 3: case 5: case 7: case 8: case 10: case 12:
    			if(day > 31)
    				return false;
    			return true;
    		case 2:
    			if (year % 4 == 0)
    				if(day > 29){
    					return false;
    				}
    				else{
    					return true;
    				}
    			if(day > 28){
    				return false;
    			}
    			return true;
    		case 4: case 6: case 9: case 11:
    			if(day > 30){
    				return false;
    			}
    			return true;
    		default:
    			return false;
    	}
    }
    
    console.log(isDate(30, 5, 2017));
    console.log(isDate(29, 2, 2016));
    console.log(isDate(29, 2, 2015));

提交回复
热议问题