How to validate a date?

前端 未结 12 1663
被撕碎了的回忆
被撕碎了的回忆 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:38
    var isDate_ = function(input) {
            var status = false;
            if (!input || input.length <= 0) {
              status = false;
            } else {
              var result = new Date(input);
              if (result == 'Invalid Date') {
                status = false;
              } else {
                status = true;
              }
            }
            return status;
          }
    

    this function returns bool value of whether the input given is a valid date or not. ex:

    if(isDate_(var_date)) {
      // statements if the date is valid
    } else {
      // statements if not valid
    }
    
    0 讨论(0)
  • 2020-11-22 04:39

    Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'? I think NOT, because the YEAR is not validated ;(

    My proposition is to use improved version of this function:

    //input in ISO format: yyyy-MM-dd
    function DatePicker_IsValidDate(input) {
            var bits = input.split('-');
            var d = new Date(bits[0], bits[1] - 1, bits[2]);
            return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
    }
    
    0 讨论(0)
  • 2020-11-22 04:39

    I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.

    var date = moment("2016-10-19");
    

    And then date.isValid() gives desired result.

    Se post HERE

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

    I just do a remake of RobG solution

    var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
    var isLeap = new Date(theYear,1,29).getDate() == 29;
    
    if (isLeap) {
      daysInMonth[1] = 29;
    }
    return theDay <= daysInMonth[--theMonth]
    
    0 讨论(0)
  • 2020-11-22 04:41

    Though this was raised long ago, still a most wanted validation. I found an interesting blog with few function.

    /* Please use these function to check the reuslt only. do not check for otherewise. other than utiljs_isInvalidDate
    
    Ex:-
    
    utiljs_isFutureDate() retuns only true for future dates. false does not mean it is not future date. it may be an invalid date.
    
    practice :
    
    call utiljs_isInvalidDate first and then use the returned date for utiljs_isFutureDate()
    
    var d = {};
    
    if(!utiljs_isInvalidDate('32/02/2012', d))
    
    if(utiljs_isFutureDate(d))
    
    //date is a future date
    
    else
    
    // date is not a future date
    
    
    
     */
    
    function utiljs_isInvalidDate(dateStr, returnDate) {
    
        /*dateStr | format should be dd/mm/yyyy, Ex:- 31/10/2017
    
         *returnDate will be in {date:js date object}.
    
         *Ex:- if you only need to check whether the date is invalid,
    
         * utiljs_isInvalidDate('03/03/2017')
    
         *Ex:- if need the date, if the date is valid,
    
         * var dt = {};
    
         * if(!utiljs_isInvalidDate('03/03/2017', dt)){
    
         *  //you can use dt.date
    
         * }
    
         */
    
        if (!dateStr)
            return true;
        if (!dateStr.substring || !dateStr.length || dateStr.length != 10)
            return true;
        var day = parseInt(dateStr.substring(0, 2), 10);
        var month = parseInt(dateStr.substring(3, 5), 10);
        var year = parseInt(dateStr.substring(6), 10);
        var fullString = dateStr.substring(0, 2) + dateStr.substring(3, 5) + dateStr.substring(6);
        if (null == fullString.match(/^\d+$/)) //to check for whether there are only numbers
            return true;
        var dt = new Date(month + "/" + day + "/" + year);
        if (dt == 'Invalid Date' || isNaN(dt)) { //if the date string is not valid, new Date will create this string instead
            return true;
        }
        if (dt.getFullYear() != year || dt.getMonth() + 1 != month || dt.getDate() != day) //to avoid 31/02/2018 like dates
            return true;
        if (returnDate)
            returnDate.date = dt;
        return false;
    }
    
    function utiljs_isFutureDate(dateStrOrObject, returnDate) {
        return utiljs_isFuturePast(dateStrOrObject, returnDate, true);
    }
    
    function utiljs_isPastDate(dateStrOrObject, returnDate) {
        return utiljs_isFuturePast(dateStrOrObject, returnDate, false);
    }
    
    function utiljs_isValidDateObjectOrDateString(dateStrOrObject, returnDate) { //this is an internal function
        var dt = {};
        if (!dateStrOrObject)
            return false;
        if (typeof dateStrOrObject.getMonth === 'function')
            dt.date = new Date(dateStrOrObject); //to avoid modifying original date
        else if (utiljs_isInvalidDate(dateStrOrObject, dt))
            return false;
        if (returnDate)
            returnDate.date = dt.date;
        return true;
    
    }
    
    function utiljs_isFuturePast(dateStrOrObject, returnDate, isFuture) { //this is an internal function, please use isFutureDate or isPastDate function
        if (!dateStrOrObject)
            return false;
        var dt = {};
        if (!utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt))
            return false;
        today = new Date();
        today.setHours(0, 0, 0, 0);
        if (dt.date)
            dt.date.setHours(0, 0, 0, 0);
        if (returnDate)
            returnDate.date = dt.date;
        //creating new date using only current d/m/y. as td.date is created with string. otherwise same day selection will not be validated.
        if (isFuture && dt.date && dt.date.getTime && dt.date.getTime() > today.getTime()) {
            return true;
        }
        if (!isFuture && dt.date && dt.date.getTime && dt.date.getTime() < today.getTime()) {
            return true;
        }
        return false;
    }
    
    function utiljs_isLeapYear(dateStrOrObject, returnDate) {
        var dt = {};
        if (!dateStrOrObject)
            return false;
        if (utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt)) {
            if (returnDate)
                returnDate.date = dt.date;
            return dt.date.getFullYear() % 4 == 0;
        }
        return false;
    }
    
    function utiljs_firstDateLaterThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
        if (!firstDate || !secondDate)
            return false;
        var dt1 = {},
        dt2 = {};
        if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
            return false;
        if (returnFirstDate)
            returnFirstDate.date = dt1.date;
        if (returnSecondDate)
            returnSecondDate.date = dt2.date;
        dt1.date.setHours(0, 0, 0, 0);
        dt2.date.setHours(0, 0, 0, 0);
        if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() > dt2.date.getTime())
            return true;
        return false;
    }
    
    function utiljs_isEqual(firstDate, secondDate, returnFirstDate, returnSecondDate) {
        if (!firstDate || !secondDate)
            return false;
        var dt1 = {},
        dt2 = {};
        if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
            return false;
        if (returnFirstDate)
            returnFirstDate.date = dt1.date;
        if (returnSecondDate)
            returnSecondDate.date = dt2.date;
        dt1.date.setHours(0, 0, 0, 0);
        dt2.date.setHours(0, 0, 0, 0);
        if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() == dt2.date.getTime())
            return true;
        return false;
    }
    
    function utiljs_firstDateEarlierThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
        if (!firstDate || !secondDate)
            return false;
        var dt1 = {},
        dt2 = {};
        if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
            return false;
        if (returnFirstDate)
            returnFirstDate.date = dt1.date;
        if (returnSecondDate)
            returnSecondDate.date = dt2.date;
        dt1.date.setHours(0, 0, 0, 0);
        dt2.date.setHours(0, 0, 0, 0);
        if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() < dt2.date.getTime())
            return true;
        return false;
    }
    

    copy the whole code into a file and include.

    hope this helps.

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

    Hi Please find the answer below.this is done by validating the date newly created

    var year=2019;
    var month=2;
    var date=31;
    var d = new Date(year, month - 1, date);
    if (d.getFullYear() != year
            || d.getMonth() != (month - 1)
            || d.getDate() != date) {
        alert("invalid date");
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题