How to validate a date?

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

    This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.

    For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):

    console.log(new Date(2009, 1, 29));
    

    The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)

    Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):

    var isActualDate = function (month, day, year) {
        var tempDate = new Date(year, --month, day);
        return month === tempDate.getMonth();
    };
    

    This isn't a complete solution and doesn't take i18n into account but it could be made more robust.

    0 讨论(0)
  • 2020-11-22 04:56

    One simple way to validate a date string is to convert to a date object and test that, e.g.

    // Expect input as d/m/y
    function isValidDate(s) {
      var bits = s.split('/');
      var d = new Date(bits[2], bits[1] - 1, bits[0]);
      return d && (d.getMonth() + 1) == bits[1];
    }
    
    ['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
      console.log(s + ' : ' + isValidDate(s))
    })

    When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.

    You can also test the bits of the date string:

    function isValidDate2(s) {
      var bits = s.split('/');
      var y = bits[2],
        m = bits[1],
        d = bits[0];
      // Assume not leap year by default (note zero index for Jan)
      var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    
      // If evenly divisible by 4 and not evenly divisible by 100,
      // or is evenly divisible by 400, then a leap year
      if ((!(y % 4) && y % 100) || !(y % 400)) {
        daysInMonth[1] = 29;
      }
      return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
    }
    
    ['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
      console.log(s + ' : ' + isValidDate2(s))
    })

    0 讨论(0)
  • 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));

    0 讨论(0)
  • 2020-11-22 04:57
    function isValidDate(year, month, day) {
            var d = new Date(year, month - 1, day, 0, 0, 0, 0);
            return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
        }
    
    0 讨论(0)
  • 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]);
    
    0 讨论(0)
  • 2020-11-22 05:02

    It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):

    const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
    function isValidDate(strDate) {
      if (!dateValidationRegex.test(strDate)) return false;
      const [m, d, y] = strDate.split('/').map(n => parseInt(n));
      return m === new Date(y, m - 1, d).getMonth() + 1;
    }
    
    ['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
      console.log(d, isValidDate(d));
    });

    0 讨论(0)
提交回复
热议问题