Подтвердить что ты не робот

Как проверить дату в формате "мм/дд/гггг" в JavaScript?

Я хочу проверить формат даты на входе, используя формат mm/dd/yyyy.

Я нашел ниже коды на одном сайте, а затем использовал его, но он не работает:

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!'); 
    } 
}

Любое предложение о том, что может быть неправильным?

4b9b3361

Ответ 1

Думаю, у Никласа есть правильный ответ на вашу проблему. Кроме того, я думаю, что следующая функция проверки даты немного легче читать:

// Validates that the input string is a valid date formatted as "mm/dd/yyyy"
function isValidDate(dateString)
{
    // First check for the pattern
    if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
        return false;

    // Parse the date parts to integers
    var parts = dateString.split("/");
    var day = parseInt(parts[1], 10);
    var month = parseInt(parts[0], 10);
    var year = parseInt(parts[2], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
        return false;

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
        monthLength[1] = 29;

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
};

Ответ 2

Я бы использовал Moment.js для проверки даты.

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

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

Ответ 3

Используйте следующее регулярное выражение для проверки:

var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
return false;
}

Это работает для меня для MM/dd/yyyy.

Ответ 4

Все кредиты идут в elian-ebbing

Просто для ленивых здесь я также предоставляю настраиваемую версию функции для формата yyyy-mm-dd.

function isValidDate(dateString)
{
    // First check for the pattern
    var regex_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;

    if(!regex_date.test(dateString))
    {
        return false;
    }

    // Parse the date parts to integers
    var parts   = dateString.split("-");
    var day     = parseInt(parts[2], 10);
    var month   = parseInt(parts[1], 10);
    var year    = parseInt(parts[0], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
    {
        return false;
    }

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
    {
        monthLength[1] = 29;
    }

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
}

Ответ 5

Кажется, что он отлично работает для дат формата mm/dd/yyyy, например:

http://jsfiddle.net/niklasvh/xfrLm/

Единственная проблема с вашим кодом заключалась в том, что:

var ExpiryDate = document.getElementById(' ExpiryDate').value;

Имелось место внутри скобок, перед идентификатором элемента. Изменено:

var ExpiryDate = document.getElementById('ExpiryDate').value;

Без каких-либо дополнительных сведений о типе данных, которые не работают, нет ничего другого, чтобы дать ввод.

Ответ 6

Функция вернет true, если заданная строка находится в правильном формате ( "MM/DD/YYYY" ), иначе она вернет false. (Я нашел этот код онлайн и немного изменил его)

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'));
            

Ответ 7

Вы можете использовать Date.parse()

Вы можете прочитать в документации MDN

Метод Date.parse() анализирует строковое представление даты и возвращает количество миллисекунд с 1 января 1970 года, 00:00:00 UTC или NaN, если строка не распознана или, в некоторых случаях, содержит недопустимые значения даты (например, 2015-02-31).

И проверьте, если результат Date.parse isNaN

let isValidDate = Date.parse('01/29/1980');

if (isNaN(isValidDate)) {
  // when is not valid date logic

  return false;
}

// when is valid date logic

Пожалуйста, обратите внимание, когда рекомендуется использовать Date.parse в MDN.

Ответ 8

Найдите в приведенном ниже коде, который позволяет выполнять проверку даты для любого из предоставленного формата для проверки начала/от и конца/до дат. Могут быть некоторые более эффективные подходы, но они придумали это. Примечание: формат датированной даты и строка даты идут рука об руку.

<script type="text/javascript">
    function validate() {

        var format = 'yyyy-MM-dd';

        if(isAfterCurrentDate(document.getElementById('start').value, format)) {
            alert('Date is after the current date.');
        } else {
            alert('Date is not after the current date.');
        }
        if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
            alert('Date is before current date.');
        } else {
            alert('Date is not before current date.');
        }
        if(isCurrentDate(document.getElementById('start').value, format)) {
            alert('Date is current date.');
        } else {
            alert('Date is not a current date.');
        }
        if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
            alert('Start/Effective Date cannot be greater than End/Expiration Date');
        } else {
            alert('Valid dates...');
        }
        if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
            alert('End/Expiration Date cannot be less than Start/Effective Date');
        } else {
            alert('Valid dates...');
        }
        if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
            alert('Dates are equals...');
        } else {
            alert('Dates are not equals...');
        }
        if (isDate(document.getElementById('start').value, format)) {
            alert('Is valid date...');
        } else {
            alert('Is invalid date...');
        }
    }

    /**
     * This method gets the year index from the supplied format
     */
    function getYearIndex(format) {

        var tokens = splitDateFormat(format);

        if (tokens[0] === 'YYYY'
                || tokens[0] === 'yyyy') {
            return 0;
        } else if (tokens[1]=== 'YYYY'
                || tokens[1] === 'yyyy') {
            return 1;
        } else if (tokens[2] === 'YYYY'
                || tokens[2] === 'yyyy') {
            return 2;
        }
        // Returning the default value as -1
        return -1;
    }

    /**
     * This method returns the year string located at the supplied index
     */
    function getYear(date, index) {

        var tokens = splitDateFormat(date);
        return tokens[index];
    }

    /**
     * This method gets the month index from the supplied format
     */
    function getMonthIndex(format) {

        var tokens = splitDateFormat(format);

        if (tokens[0] === 'MM'
                || tokens[0] === 'mm') {
            return 0;
        } else if (tokens[1] === 'MM'
                || tokens[1] === 'mm') {
            return 1;
        } else if (tokens[2] === 'MM'
                || tokens[2] === 'mm') {
            return 2;
        }
        // Returning the default value as -1
        return -1;
    }

    /**
     * This method returns the month string located at the supplied index
     */
    function getMonth(date, index) {

        var tokens = splitDateFormat(date);
        return tokens[index];
    }

    /**
     * This method gets the date index from the supplied format
     */
    function getDateIndex(format) {

        var tokens = splitDateFormat(format);

        if (tokens[0] === 'DD'
                || tokens[0] === 'dd') {
            return 0;
        } else if (tokens[1] === 'DD'
                || tokens[1] === 'dd') {
            return 1;
        } else if (tokens[2] === 'DD'
                || tokens[2] === 'dd') {
            return 2;
        }
        // Returning the default value as -1
        return -1;
    }

    /**
     * This method returns the date string located at the supplied index
     */
    function getDate(date, index) {

        var tokens = splitDateFormat(date);
        return tokens[index];
    }

    /**
     * This method returns true if date1 is before date2 else return false
     */
    function isBefore(date1, date2, format) {
        // Validating if date1 date is greater than the date2 date
        if (new Date(getYear(date1, getYearIndex(format)), 
                getMonth(date1, getMonthIndex(format)) - 1, 
                getDate(date1, getDateIndex(format))).getTime()
            > new Date(getYear(date2, getYearIndex(format)), 
                getMonth(date2, getMonthIndex(format)) - 1, 
                getDate(date2, getDateIndex(format))).getTime()) {
            return true;
        } 
        return false;                
    }

    /**
     * This method returns true if date1 is after date2 else return false
     */
    function isAfter(date1, date2, format) {
        // Validating if date2 date is less than the date1 date
        if (new Date(getYear(date2, getYearIndex(format)), 
                getMonth(date2, getMonthIndex(format)) - 1, 
                getDate(date2, getDateIndex(format))).getTime()
            < new Date(getYear(date1, getYearIndex(format)), 
                getMonth(date1, getMonthIndex(format)) - 1, 
                getDate(date1, getDateIndex(format))).getTime()
            ) {
            return true;
        } 
        return false;                
    }

    /**
     * This method returns true if date1 is equals to date2 else return false
     */
    function isEquals(date1, date2, format) {
        // Validating if date1 date is equals to the date2 date
        if (new Date(getYear(date1, getYearIndex(format)), 
                getMonth(date1, getMonthIndex(format)) - 1, 
                getDate(date1, getDateIndex(format))).getTime()
            === new Date(getYear(date2, getYearIndex(format)), 
                getMonth(date2, getMonthIndex(format)) - 1, 
                getDate(date2, getDateIndex(format))).getTime()) {
            return true;
        } 
        return false;
    }

    /**
     * This method validates and returns true if the supplied date is 
     * equals to the current date.
     */
    function isCurrentDate(date, format) {
        // Validating if the supplied date is the current date
        if (new Date(getYear(date, getYearIndex(format)), 
                getMonth(date, getMonthIndex(format)) - 1, 
                getDate(date, getDateIndex(format))).getTime()
            === new Date(new Date().getFullYear(), 
                    new Date().getMonth(), 
                    new Date().getDate()).getTime()) {
            return true;
        } 
        return false;                
    }

    /**
     * This method validates and returns true if the supplied date value 
     * is before the current date.
     */
    function isBeforeCurrentDate(date, format) {
        // Validating if the supplied date is before the current date
        if (new Date(getYear(date, getYearIndex(format)), 
                getMonth(date, getMonthIndex(format)) - 1, 
                getDate(date, getDateIndex(format))).getTime()
            < new Date(new Date().getFullYear(), 
                    new Date().getMonth(), 
                    new Date().getDate()).getTime()) {
            return true;
        } 
        return false;                
    }

    /**
     * This method validates and returns true if the supplied date value 
     * is after the current date.
     */
    function isAfterCurrentDate(date, format) {
        // Validating if the supplied date is before the current date
        if (new Date(getYear(date, getYearIndex(format)), 
                getMonth(date, getMonthIndex(format)) - 1, 
                getDate(date, getDateIndex(format))).getTime()
            > new Date(new Date().getFullYear(),
                    new Date().getMonth(), 
                    new Date().getDate()).getTime()) {
            return true;
        } 
        return false;                
    }

    /**
     * This method splits the supplied date OR format based 
     * on non alpha numeric characters in the supplied string.
     */
    function splitDateFormat(dateFormat) {
        // Spliting the supplied string based on non characters
        return dateFormat.split(/\W/);
    }

    /*
     * This method validates if the supplied value is a valid date.
     */
    function isDate(date, format) {                
        // Validating if the supplied date string is valid and not a NaN (Not a Number)
        if (!isNaN(new Date(getYear(date, getYearIndex(format)), 
                getMonth(date, getMonthIndex(format)) - 1, 
                getDate(date, getDateIndex(format))))) {                    
            return true;
        } 
        return false;                                      
    }
</script>

Ниже приведен фрагмент HTML

<input type="text" name="start" id="start" size="10" value="" />
<br/>
<input type="text" name="end" id="end" size="10" value="" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate();" />

Ответ 9

Вот один фрагмент для проверки действительной даты:

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));

Ответ 10

Это нормально, если вы хотите проверить валидацию дд/мм/гггг

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
            

Ответ 12

Я вытащил большую часть этого кода из другого сообщения, найденного здесь. Я изменил его для своих целей. Это хорошо работает для того, что мне нужно. Это может помочь в вашей ситуации.

$(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 );
});

Ответ 13

function fdate_validate(vi)
{
  var parts =vi.split('/');
  var result;
  var mydate = new Date(parts[2],parts[1]-1,parts[0]);
  if (parts[2] == mydate.getYear() && parts[1]-1 == mydate.getMonth() && parts[0] == mydate.getDate() )
  {result=0;}
  else
  {result=1;}
  return(result);
}

Ответ 14

Как и ответ Элиана Эббинга, но поддерживайте "\", "/", ".", "-", "" разделители

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; 
}

Ответ 15

Момент действительно хороший, чтобы решить это. Я не вижу смысла добавлять сложность, просто чтобы проверить дату... посмотрите на момент: http://momentjs.com/

HTML:

<input class="form-control" id="date" name="date" onchange="isValidDate(this);" placeholder="DD/MM/YYYY" type="text" value="">

Сценарий:

 function isValidDate(dateString)  {
    var dateToValidate = dateString.value
    var isValid = moment(dateToValidate, 'MM/DD/YYYY',true).isValid()
    if (isValid) {
        dateString.style.backgroundColor = '#FFFFFF';
    } else {
        dateString.style.backgroundColor = '#fba';
    }   
};

Ответ 16

Первая строка даты преобразуется в формат даты js и преобразуется в формат строки, затем сравнивается с исходной строкой.

function dateValidation(){
    var dateString = "34/05/2019"
    var dateParts = dateString.split("/");
    var date= new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);

    var isValid = isValid( dateString, date );
    console.log("Is valid date: " + isValid);
}

function isValidDate(dateString, date) {
    var newDateString = ( date.getDate()<10 ? ('0'+date.getDate()) : date.getDate() )+ '/'+ ((date.getMonth() + 1)<10? ('0'+(date.getMonth() + 1)) : (date.getMonth() + 1) )  + '/' +  date.getFullYear();
    return ( dateString == newDateString);
}

Ответ 17

var date = new Date(date_string)

возвращает литерал 'Invalid Date' для любой недопустимой даты_строки.

Примечание.. См. комментарий ниже.