How to validate date with format “mm/dd/yyyy” in J

2019-01-01 08:26发布

I want to validate the date format on an input using the format mm/dd/yyyy.

I found below codes in one site and then used it but it doesn't work:

function isDate(ExpiryDate) { 
    var objDate,  // date object initialized from the ExpiryDate string 
        mSeconds, // ExpiryDate in milliseconds 
        day,      // day 
        month,    // month 
        year;     // year 
    // date length should be 10 characters (no more no less) 
    if (ExpiryDate.length !== 10) { 
        return false; 
    } 
    // third and sixth character should be '/' 
    if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') { 
        return false; 
    } 
    // extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy) 
    // subtraction will cast variables to integer implicitly (needed 
    // for !== comparing) 
    month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0 
    day = ExpiryDate.substring(3, 5) - 0; 
    year = ExpiryDate.substring(6, 10) - 0; 
    // test year range 
    if (year < 1000 || year > 3000) { 
        return false; 
    } 
    // convert ExpiryDate to milliseconds 
    mSeconds = (new Date(year, month, day)).getTime(); 
    // initialize Date() object from calculated milliseconds 
    objDate = new Date(); 
    objDate.setTime(mSeconds); 
    // compare input date and parts from Date() object 
    // if difference exists then date isn't valid 
    if (objDate.getFullYear() !== year || 
        objDate.getMonth() !== month || 
        objDate.getDate() !== day) { 
        return false; 
    } 
    // otherwise return true 
    return true; 
}

function checkDate(){ 
    // define date string to test 
    var ExpiryDate = document.getElementById(' ExpiryDate').value; 
    // check date and print message 
    if (isDate(ExpiryDate)) { 
        alert('OK'); 
    } 
    else { 
        alert('Invalid date format!'); 
    } 
}

Any suggestion about what could be wrong?

14条回答
千与千寻千般痛.
2楼-- · 2019-01-01 09:08

Similar to Elian Ebbing answer, but support "\", "/", ".", "-", " " delimiters

function js_validate_date_dmyyyy(js_datestr)
{
    var js_days_in_year = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
    var js_datepattern = /^(\d{1,2})([\.\-\/\\ ])(\d{1,2})([\.\-\/\\ ])(\d{4})$/;

    if (! js_datepattern.test(js_datestr)) { return false; }

    var js_match = js_datestr.match(js_datepattern);
    var js_day = parseInt(js_match[1]);
    var js_delimiter1 = js_match[2];
    var js_month = parseInt(js_match[3]);
    var js_delimiter2 = js_match[4];
    var js_year = parseInt(js_match[5]);                            

    if (js_is_leap_year(js_year)) { js_days_in_year[2] = 29; }

    if (js_delimiter1 !== js_delimiter2) { return false; } 
    if (js_month === 0  ||  js_month > 12)  { return false; } 
    if (js_day === 0  ||  js_day > js_days_in_year[js_month])   { return false; } 

    return true;
}

function js_is_leap_year(js_year)
{ 
    if(js_year % 4 === 0)
    { 
        if(js_year % 100 === 0)
        { 
            if(js_year % 400 === 0)
            { 
                return true; 
            } 
            else return false; 
        } 
        else return true; 
    } 
    return false; 
}
查看更多
与风俱净
3楼-- · 2019-01-01 09:09

The function will return true if the given string is in the right format('MM/DD/YYYY') else it will return false. (I found this code online & modified it a little)

function isValidDate(date) {
    var temp = date.split('/');
    var d = new Date(temp[2] + '/' + temp[0] + '/' + temp[1]);
    return (d && (d.getMonth() + 1) == temp[0] && d.getDate() == Number(temp[1]) && d.getFullYear() == Number(temp[2]));
}

console.log(isValidDate('02/28/2015'));
            

查看更多
时光乱了年华
4楼-- · 2019-01-01 09:09

Here is one snippet to check for valid date:

function validateDate(dateStr) {
   const regExp = /^(\d\d?)\/(\d\d?)\/(\d{4})$/;
   let matches = dateStr.match(regExp);
   let isValid = matches;
   let maxDate = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
   
   if (matches) {
     const month = parseInt(matches[1]);
     const date = parseInt(matches[2]);
     const year = parseInt(matches[3]);
     
     isValid = month <= 12 && month > 0;
     isValid &= date <= maxDate[month] && date > 0;
     
     const leapYear = (year % 400 == 0)
        || (year % 4 == 0 && year % 100 != 0);
     isValid &= month != 2 || leapYear || date <= 28; 
   }
   
   return isValid
}

console.log(['1/1/2017', '01/1/2017', '1/01/2017', '01/01/2017', '13/12/2017', '13/13/2017', '12/35/2017'].map(validateDate));

查看更多
还给你的自由
5楼-- · 2019-01-01 09:09

I pulled most of this code from another post found here. I have modified it for my purposes. This works well for what I need. It may help with your situation.

$(window).load(function() {
  function checkDate() {
    var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
    var valDate = $(this).val();
    if ( valDate.match( dateFormat )) {
      $(this).css("border","1px solid #cccccc","color", "#555555", "font-weight", "normal");
      var seperator1 = valDate.split('/');
      var seperator2 = valDate.split('-');

      if ( seperator1.length > 1 ) {
        var splitdate = valDate.split('/');
      } else if ( seperator2.length > 1 ) {
        var splitdate = valDate.split('-');
      }

      var dd = parseInt(splitdate[0]);
      var mm = parseInt(splitdate[1]);
      var yy = parseInt(splitdate[2]);
      var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];

      if ( mm == 1 || mm > 2 ) {
        if ( dd > ListofDays[mm - 1] ) {
          $(this).val("");
          $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
          alert('Invalid Date! You used a date which does not exist in the known calender.');
          return false;
        }
      }

      if ( mm == 2 ) {
       var lyear = false;
        if ( (!(yy % 4) && yy % 100) || !(yy % 400) ){
          lyear = true;
        }

        if ( (lyear==false) && (dd>=29) ) {
          $(this).val("");
          $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
          alert('Invalid Date! You used Feb 29th for an invalid leap year');
          return false;
        }

        if ( (lyear==true) && (dd>29) ) {
          $(this).val("");
          $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
          alert('Invalid Date! You used a date greater than Feb 29th in a valid leap year');
          return false;
        }
     }
    } else {
      $(this).val("");
      $(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
      alert('Date format was invalid! Please use format mm/dd/yyyy');
      return false;
    }
  };

  $('#from_date').change( checkDate );
  $('#to_date').change( checkDate );
});
查看更多
深知你不懂我心
6楼-- · 2019-01-01 09:13

I would use Moment.js for date validation.

alert(moment("05/22/2012", 'MM/DD/YYYY',true).isValid()); //true

Jsfiddle: http://jsfiddle.net/q8y9nbu5/

查看更多
泛滥B
7楼-- · 2019-01-01 09:16

It's ok if you want to check validate dd/MM/yyyy

function isValidDate(date) {
    var temp = date.split('/');
    var d = new Date(temp[1] + '/' + temp[0] + '/' + temp[2]);
     return (d && (d.getMonth() + 1) == temp[1] && d.getDate() == Number(temp[0]) && d.getFullYear() == Number(temp[2]));
}

alert(isValidDate('29/02/2015')); // it not exist ---> false
            

查看更多
登录 后发表回答