【问题标题】:Javascript: how to validate dates in format MM-DD-YYYY?Javascript:如何验证格式为 MM-DD-YYYY 的日期?
【发布时间】:2010-09-21 13:07:31
【问题描述】:

我在这里看到了一个可能的答案,但那是针对 YYYY-MM-DD:JavaScript date validation

我为 MM-DD-YYYY 修改了上面的代码代码,但我仍然无法让它工作:

String.prototype.isValidDate = function() 
{
     var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
     var matches = IsoDateRe.exec(this);
     if (!matches) return false;
     var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
     return ((composedDate.getMonth() == (matches[1] - 1)) &&
      (composedDate.getDate() == matches[2]) &&
      (composedDate.getFullYear() == matches[3]));
}

我怎样才能让上述代码适用于 MM-DD-YYYY 和更好的 MM/DD/YYYY?

谢谢。

【问题讨论】:

标签: javascript validation date


【解决方案1】:
function isValidDate(date)
{
    var matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[2];
    var m = matches[1] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));

它有效。 (使用 Firebug 测试,因此使用了 console.log()。)

【讨论】:

  • @ChristianVielma 真的吗?你试过代码吗?在哪个浏览器上?
  • 不,你是对的,只是再次测试它,它是好的。很抱歉!
  • 如果您只使用一位数字表示月份,它确实会失败。例如,“2013 年 1 月 31 日”将失败。此外,“01-1-2013”​​这一天使用一位数字,或者如果您使用“01-01-13”这一年两位数字
  • 使用这个正则表达式接受一位数字的日期和月份值。 /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/
  • @AnilNamde 编辑了我的答案以接受 1 位数的日期或月份。我不会编辑它,因为它可能有它的用途(根据上面的 cmets 判断),但这不是最初要求的......
【解决方案2】:
function isValidDate(date) {
        var valid = true;

        date = date.replace('/-/g', '');

        var month = parseInt(date.substring(0, 2),10);
        var day   = parseInt(date.substring(2, 4),10);
        var year  = parseInt(date.substring(4, 8),10);

        if(isNaN(month) || isNaN(day) || isNaN(year)) return false;

        if((month < 1) || (month > 12)) valid = false;
        else if((day < 1) || (day > 31)) valid = false;
        else if(((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30)) valid = false;
        else if((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29)) valid = false;
        else if((month == 2) && ((year % 100) == 0) && (day > 29)) valid = false;
        else if((month == 2) && (day > 28)) valid = false;

    return valid;
}

这会检查每个月的有效天数和有效的闰年天数。

【讨论】:

  • 仅供参考,您需要更正您的第二个和第四个 elseIf。 #2 删除(月 ==7),因为 7 月确实有 31 天。 #4 变化((年 % 100)== 0)|| (day > 28)) 到 ((year % 100) == 0) && (day > 28))。这指定必须满足所有三个条件。否则,如果 Day > 28,无论是否是闰年,该函数都将返回 false。无论如何,你会得到 +1,因为这对我有很大帮助。
  • 仅供参考,对于未来的读者,您还必须将以下内容应用于您的代码,以使上述内容正常工作。将上面看到的 date.replace 更改为 "date.replace(/-/g, '')" 以确保它替换所有连字符,而不仅仅是第一个。此外,如果 date.substring(2,4) 是“08”或“09”,您将在 parseInt 中遇到 1:1000000 设计怪癖,其中包含您的 day 变量。有关详细信息和解决方案,请参阅下一个链接。 support.microsoft.com/kb/191434
  • 如果我没记错的话,应该写不带 ' 。 date = date.replace(/-/g, '');否则它会寻找像“/-/g”这样的字符串。
  • 我 100% 确定您的闰年代码有问题(即使是 2001 年 2 月 29 日这样的日期,它也被验证为真实)
  • @sataniccrow 现在已修复
【解决方案3】:

如何以“ANY”日期格式验证日期?我一直在使用 DateJS 库并将其添加到现有表单中,以确保我获得按我想要的方式格式化的有效日期和时间。用户甚至可以输入诸如“现在”和“明天”之类的内容,它将被转换为有效日期。

这里是 dateJS 库: http://www.datejs.com/

这是我写的一个 jQuery 技巧: http://www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm

【讨论】:

    【解决方案4】:

    我会使用Moment.js 来完成这项任务。它使得解析日期非常容易,它还支持以正确的格式检测无效日期1。例如,考虑this example

    var formats = ['MM-DD-YYYY', 'MM/DD/YYYY']
    
    moment('11/28/1981', formats).isValid()  // true
    moment('2-29-2003', formats).isValid()   // false (not leap year)
    moment('2-29-2004', formats).isValid()   // true  (leap year)
    

    首先moment(.., formats) 用于根据提供的本地化格式解析输入。然后在生成的时刻对象上调用isValid 函数,这样我们就可以真正判断它是否是有效日期。

    这可以用来简单地派生 isValidDate 方法:

    String.prototype.isValidDate = function() {
        var formats = ['MM-DD-YYYY', 'MM/DD/YYYY'];
        return moment("" + this, formats).isValid();
    }
    

    1 因为我几乎找不到关于此事的评论,所以我只会将 moment.js 用于 Gregorian calendar 涵盖的日期。可能有其他(包括历史或科学)日历的插件。

    【讨论】:

      【解决方案5】:

      我使用这个正则表达式来验证 MM-DD-YYYY:

      function isValidDate(subject){
        if (subject.match(/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/)){
          return true;
        }else{
          return false;
        }
      }
      

      它将仅匹配有效月份,您可以使用 / - 或 .作为分隔符。

      【讨论】:

      • 它将返回 2011 年 2 月 29 日为真,但它应该返回假
      • 根据您的函数,“02-29-2011”是有效日期,甚至“02-30-2011”、“02-31-2011”也是有效日期。
      【解决方案6】:

      此函数将验证日期是否正确或格式是否正确:DD/MM/YYYY。

      function isValidDate(date)
      {
          var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
          if (matches == null) return false;
          var d = matches[1];
          var m = matches[2]-1;
          var y = matches[3];
          var composedDate = new Date(y, m, d);
          return composedDate.getDate() == d &&
                 composedDate.getMonth() == m &&
                 composedDate.getFullYear() == y;
      }
      console.log(isValidDate('10-12-1961'));
      console.log(isValidDate('12/11/1961'));
      console.log(isValidDate('02-11-1961'));
      console.log(isValidDate('12/01/1961'));
      console.log(isValidDate('13-11-1961'));
      console.log(isValidDate('11-31-1961'));
      console.log(isValidDate('11-31-1061'));
      

      【讨论】:

        【解决方案7】:

        有什么不好的?这是一个经过测试的版本:

        String.prototype.isValidDate = function()   {
        
            const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
            if (!match || match.length !== 4) {
                return false
            }
        
            const test = new Date(match[3], match[1] - 1, match[2]);
        
            return (
                (test.getMonth() == match[1] - 1) &&
                (test.getDate() == match[2]) &&
                (test.getFullYear() == match[3])
            );
        }
        
        var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
        alert(date.isValidDate() ); // true
        

        【讨论】:

        • 如果没有找到匹配项,那么 new Date(match[3], match[1] - 1, match[2]);不会工作 - 更新:修复它
        【解决方案8】:

        您可以通过将函数的前两行更改为这样来稍微简化它:

        var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
        

        或者,只是将RegExp构造函数的参数改为

        ^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$
        

        【讨论】:

          【解决方案9】:

          简单的解决方法

          var day = document.getElementById("DayTextBox").value;
          
          var regExp = /^([1-9]|[1][012])\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;
          
          return regExp.test(day);
          

          【讨论】:

          • 根据您的代码,“02-29-2011”是有效日期,甚至“02-30-2011”、“02-31-2011”也是有效日期。
          【解决方案10】:

          将此函数传递给日期,格式为 //10-10-2012 和对象 ID。

          function isValidDateFormat(date, id)
          {
            var todayDate = new Date();
            var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
          
            if (matches == null)
            {
             if(date != '__-__-____')
              {
                alert('Please enter valid date');
              }
            }
            else
            {
              var day    = 31;
              var month  = 12;
              var b_date = date.split("-");
              if(b_date[0] <= day)
              {
                if(b_date[1] <= month)
                {
                  if(b_date[2] >= 1900 && b_date[2] <= todayDate.getFullYear())
                  {
                    return true;
                  }
                  else
                  {
                    $("#"+id).val('');
                    alert('Please enter valid Year'); 
                  }         
                }
                else
                {
                  $("#"+id).val('');
                  alert('Please enter valid Month');    
                } 
              }
              else
              {
                alert('Please enter valid Day');
                $("#"+id).val('');  
              }
            }
          }
          

          【讨论】:

          • 你能解释一下为什么这里需要 jQuery 吗?
          【解决方案11】:

          这是用于验证格式 dd.mm.yyyy 中的日期字符串。自定义它很容易。您只需要在 isValidDate() 中调整 pos1 和 pos2。

          var dtCh="."; var minYear=1900;

          function isInteger(s){
              var i;
              for (i = 0; i < s.length; i++){   
                  // Check that current character is number.
                  var c = s.charAt(i);
                  if (((c < "0") || (c > "9"))) return false;
              }
              // All characters are numbers.
              return true;
          }
          
          function stripCharsInBag(s, bag){
              var i;
              var returnString = "";
              // Search through string's characters one by one.
              // If character is not in bag, append to returnString.
              for (i = 0; i < s.length; i++){   
                  var c = s.charAt(i);
                  if (bag.indexOf(c) == -1) returnString += c;
              }
              return returnString;
          }
          
          function daysInFebruary (year){
              // February has 29 days in any year evenly divisible by four,
              // EXCEPT for centurial years which are not also divisible by 400.
              return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
          }
          function DaysArray(n) {
              for (var i = 1; i <= n; i++) {
                  this[i] = 31;
                  if (i==4 || i==6 || i==9 || i==11) {
                      this[i] = 30;
                  }
                  if (i==2) {
                      this[i] = 29;
                  }
             } 
             return this;
          }
          
          function isValidDate(dtStr){
              var daysInMonth = DaysArray(12);
              var pos1=dtStr.indexOf(dtCh);
              var pos2=dtStr.indexOf(dtCh,pos1+1);
              var strDay=dtStr.substring(0,pos1);
              var strMonth=dtStr.substring(pos1+1,pos2);
              var strYear=dtStr.substring(pos2+1);
              strYr=strYear;
              if (strDay.charAt(0)=="0" && strDay.length>1) 
                  strDay=strDay.substring(1);
              if (strMonth.charAt(0)=="0" && strMonth.length>1) 
                  strMonth=strMonth.substring(1);
              for (var i = 1; i <= 3; i++) {
                  if (strYr.charAt(0)=="0" && strYr.length>1) 
                      strYr=strYr.substring(1);
              }
              month=parseInt(strMonth);
              day=parseInt(strDay);
              year=parseInt(strYr);
              if (pos1==-1 || pos2==-1){
                  alert("The date format should be : dd.mm.yyyy");
                  return false;
              }
              if (strMonth.length<1 || month<1 || month>12){
                  alert("Please enter a valid month");
                  return false;
              }
              if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
                  alert("Please enter a valid day");
                  return false;
              }
              if (strYear.length != 4 || year==0 || year<minYear){
                  alert("Please enter a valid 4 digit year after "+minYear);
                  return false;
              }
              if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
                  alert("Please enter a valid date");
                  return false;
              }
              return true;
          }
          

          【讨论】:

            【解决方案12】:
            if (document.getElementById('expiryDay').value != test(match("/^([0-9]{2})\/([0-9]{2})$/"))){
                 alert("Enter the date in two digit month flowed by two digits year \n");
            }
            

            【讨论】:

              【解决方案13】:
              <!DOCTYPE html>  
              <html>  
              <head>  
              
              <title></title>  
               <script>
                   function dateCheck(inputText) {
                       debugger;
              
                       var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
              
                       var flag = 1;
              
                       if (inputText.value.match(dateFormat)) {
                           document.myForm.dateInput.focus();
              
                           var inputFormat1 = inputText.value.split('/');
                           var inputFormat2 = inputText.value.split('-');
                           linputFormat1 = inputFormat1.length;
                           linputFormat2 = inputFormat2.length;
              
                           if (linputFormat1 > 1) {
                               var pdate = inputText.value.split('/');
                           }
                           else if (linputFormat2 > 1) {
                               var pdate = inputText.value.split('-');
                           }
                           var date = parseInt(pdate[0]);
                           var month = parseInt(pdate[1]);
                           var year = parseInt(pdate[2]);
              
                           var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
                           if (month == 1 || month > 2) {
                               if (date > ListofDays[month - 1]) {
                                   alert("Invalid date format!");
                                   return false;
                               }
                           }
              
                           if (month == 2) {
                               var leapYear = false;
              
                               if ((!(year % 4) && year % 100) || !(year % 400)) {
                                   leapYear = true;
              
                               }
                               if ((leapYear == false) && (date >= 29)) {
                                   alert("Invalid date format!");
                                   return false;
                               }
                               if ((leapYear == true) && (date > 29)) {
                                   alert("Invalid date format!");
                                   return false;
                               }
                           }
                           if (flag == 1) {
                               alert("Valid Date");
                           }
                       }
                       else {
                           alert("Invalid date format!");
                           document.myForm.dateInput.focus();
                           return false;
                       }
                   }
                   function restrictCharacters(evt) {
              
                       evt = (evt) ? evt : window.event;
                       var charCode = (evt.which) ? evt.which : evt.keyCode;
                       if (((charCode >= '48') && (charCode <= '57')) || (charCode == '47')) {
                           return true;
                       }
                       else {
                           return false;
                       }
                   }
              
              
               </script>   
              </head>
              
              
              
              <body>  
                  <div>  
                      <form name="myForm" action="#">   
                          <table>
                              <tr>
                                  <td>Enter Date</td>
                                  <td><input type="text" onkeypress="return restrictCharacters(event);" name="dateInput"/></td>
                                  <td></td>
                                  <td><span id="span2"></span></td>
                              </tr>
              
                              <tr>
                                  <td></td>
                                  <td><input type="button" name="submit" value="Submit" onclick="dateCheck(document.myForm.dateInput)"  /></td>
                              </tr>
                          </table>
                      </form>  
                  </div>   
              </body>  
              </html> 
              

              【讨论】:

                【解决方案14】:

                请在下面的代码中找到可以对任何提供的格式执行日期验证或根据用户区域设置来验证开始/开始日期和结束/结束日期。可能有一些更好的方法,但已经想出了这个。已针对以下格式对其进行了测试:MM/dd/yyyy、dd/MM/yyyy、yyyy-MM-dd、yyyy.MM.dd、yyyy/MM/dd 和 dd-MM-yyyy。

                注意提供的日期格式和日期字符串齐头并进。

                <script type="text/javascript">
                function validate(format) {
                
                    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;                                      
                }
                

                下面是 HTML sn-p

                    <input type="text" name="start" id="start" size="10" value="05/31/2016" />
                <br/> 
                <input type="text" name="end" id="end" size="10" value="04/28/2016" />
                <br/>
                <input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />
                

                【讨论】:

                  【解决方案15】:

                  如果您的日期需要匹配 DD.MM.YYYY 并使用 AngularJS,请使用以下代码:

                  $scope.validDate = function(value){
                              var matches = /^(\d{1,2})[.](\d{1,2})[.](\d{4})$/.exec(value);
                              if (matches == null) return false;
                              var d = matches[1];
                              var m = matches[2] - 1;
                              var y = matches[3];
                              var composedDate = new Date(y, m, d);
                              return composedDate.getDate() == d &&
                                  composedDate.getMonth() == m &&
                                  composedDate.getFullYear() == y;
                          };
                              console.log($scope.validDate('22.04.2001'));
                              console.log($scope.validDate('03.10.2001'));
                              console.log($scope.validDate('30.02.2001'));
                              console.log($scope.validDate('23.09.2016'));
                              console.log($scope.validDate('29.02.2016'));
                              console.log($scope.validDate('31.02.2016'));
                  

                  有关范围对象的更多信息,请参阅here。如果没有 AngularJS,只需将第一行更改为:

                  ValidDate = new function(value) {
                  

                  然后调用它:

                  var MyDate= ValidDate('29.09.2016');
                  

                  【讨论】:

                  • 这不是对原始问题的回答,但我看到问题已更改为 JS 和日期的某种知识库文章。您能否添加一些有关 $scope 对象的信息,据我所知,它不是标准对象,会产生对象引用错误。
                  • 我在我的 AngularJs 项目中使用了这个解决方案。 $Scope link 是一个引用应用程序模型的对象。如果将此代码粘贴到没有 AngularJs 的项目中,则必须删除 $scope 对象才能使其工作。
                  • 感谢您的澄清,现在答案对我来说很有意义。
                  【解决方案16】:

                  DateFormat = DD.MM.YYYY 或 D.M.YYYY

                  function dateValidate(val){ 
                  var dateStr = val.split('.'); 
                    var date = new Date(dateStr[2], dateStr[1]-1, dateStr[0]); 
                    if(date.getDate() == dateStr[0] && date.getMonth()+1 == dateStr[1] && date.getFullYear() == dateStr[2])
                    { return date; }
                    else{ return 'NotValid';} 
                  }
                  

                  【讨论】:

                    【解决方案17】:

                    试试这个:

                    function validateDate(dates){
                        re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;     
                        var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
                    
                                if(regs = dates.match(re)) {
                                        // day value between 1 and 31
                                        if(regs[1] < 1 || regs[1] > 31) {                    
                                          return false;
                                        }
                                        // month value between 1 and 12
                                        if(regs[2] < 1 || regs[2] > 12) {                         
                                          return false;
                                        }
                    
                                        var maxday=days[regs[2]-1];
                    
                                        if(regs[2]==2){
                                            if(regs[3]%4==0){
                                                maxday=maxday+1;                                
                                            }
                                        }
                    
                                        if(regs[1]>maxday){
                                            return false;
                                        }
                    
                                        return true;
                                  }else{
                                      return false;
                                  }                   
                    }
                    

                    【讨论】:

                      【解决方案18】:

                      德语变体,但可以适应 Iso

                      export function isLeapYear(year) {
                        return (
                          year % 4 === 0 && (year % 100 != 0 || year % 1000 === 0 || year % 400 === 0)
                        )
                      }
                      
                      export function isValidGermanDate(germanDate) {
                        if (
                          !germanDate ||
                          germanDate.length < 5 ||
                          germanDate.split('.').length < 3
                        ) {
                          return false
                        }
                      
                        const day = parseInt(germanDate.split('.')[0])
                        const month = parseInt(germanDate.split('.')[1])
                        const year = parseInt(germanDate.split('.')[2])
                      
                        if (isNaN(month) || isNaN(day) || isNaN(year)) {
                          return false
                        }
                      
                        if (month < 1 || month > 12) {
                          return false
                        }
                      
                        if (day < 1 || day > 31) {
                          return false
                        }
                      
                        if ((month === 4 || month === 6 || month === 9 || month === 11) && day > 30) {
                          return false
                        }
                      
                        if (isLeapYear(year)) {
                          if (month === 2 && day > 29) {
                            return false
                          }
                        } else {
                          if (month === 2 && day > 28) {
                            return false
                          }
                        }
                      
                        return true
                      }
                      

                      【讨论】:

                        【解决方案19】:

                        短而快。

                        function dateValid(date) {
                          var match = date.match(/^(\d\d)-(\d\d)-(\d{4})$/) || [];
                          var m = (match[1] | 0) - 1;
                          var d = match[2] | 0;
                          var y = match[3] | 0;
                          return !(
                              m < 0 ||                     // Before January
                              m > 11 ||                    // After December
                              d < 1 ||                     // Before the 1st of the month
                              d - 30 > (2773 >> m & 1) ||  // After the 30th or 31st of the month using bitmap
                              m == 1 && d - 28 >           // After the 28th or 29th of February depending on leap year
                                  (!(y % 4) && y % 100 || !(y % 400)));
                        }
                        
                        console.log('02-29-2000', dateValid('02-29-2000'));
                        console.log('02-29-2001', dateValid('02-29-2001'));
                        console.log('12-31-1970', dateValid('12-31-1970'));
                        console.log('Hello', dateValid('Hello'));

                        【讨论】:

                        • 请在您的代码中添加一些解释,以便其他人可以从中学习——例如,2741 的那部分是关于什么的?
                        • @NicoHaase 添加了一些代码 cmets。 2741 是一个位图,其中 1 表示一个月有 31 天,0 表示没有。
                        • @AdamLeggett 将 (!(y % 4) &amp;&amp; y % 100 || !(y % 400))) 替换为 !(y%4 || (!(y%100) &amp;&amp; y%400)) ) 修复了通过非千禧年闰年测试发现的错误 - y % 100 表达式未转换为布尔值,因此不会强制执行在数值比较中到1
                        【解决方案20】:

                        @Adam Leggett 对上面的“Short and Fast”进行了扩展,因为像“02/30/2020”这样的情况应该返回true,而它应该是false。不过我真的很喜欢位图......

                        对于 MM/DD/YYYY 日期格式验证:

                        const dateValid = (date) => {
                          const isLeapYear = (yearNum) => {
                            return ((yearNum % 100 === 0) ? (yearNum % 400 === 0) : (yearNum % 4 === 0))?
                              1:
                              0;
                          }
                          const match = date.match(/^(\d\d)\/(\d\d)\/(\d{4})$/) || [];
                          const month = (match[1] | 0) - 1;
                          const day = match[2] | 0;
                          const year = match[3] | 0;
                        
                        const dateEval=!( month < 0 ||                     // Before January
                              month > 11 ||                    // After December
                              day < 1 ||                     // Before the 1st of the month
                              day - 30 > (2773 >> month & 1) ||
                              month === 1 && day - 28 > isLeapYear(year) 
                              // Day is 28 or 29, month is 02, year is leap year ==> true
                              );
                        
                        return `\nDate: ${date}\n\n     
                          Valid Date?: ${dateEval}\n
                          =======================================`
                        }
                        
                        console.log(dateValid('02/28/2020')) // true
                        console.log(dateValid('02/29/2020')) // true
                        console.log(dateValid('02/30/2020')) // false
                        console.log(dateValid('01/31/2020')) // true
                        console.log(dateValid('01/31/2000')) // true
                        console.log(dateValid('04/31/2020')) // false
                        console.log(dateValid('04/31/2000')) // false
                        console.log(dateValid('04/30/2020')) // true
                        console.log(dateValid('01/32/2020')) // false
                        console.log(dateValid('02/28/2021')) // true
                        console.log(dateValid('02/29/2021')) // false
                        console.log(dateValid('02/30/2021')) // false
                        console.log(dateValid('02/28/2000')) // true
                        console.log(dateValid('02/29/2000')) // true
                        console.log(dateValid('02/30/2000')) // false
                        console.log(dateValid('02/28/2001')) // true
                        console.log(dateValid('02/29/2001')) // false
                        console.log(dateValid('02/30/2001')) // false
                        

                        对于 MM-DD-YYYY 日期格式验证:将 match 模式中的 \/ 替换为 -

                        【讨论】:

                          【解决方案21】:
                          <script language = "Javascript">
                          // Declaring valid date character, minimum year and maximum year
                          var dtCh= "/";
                          var minYear=1900;
                          var maxYear=2100;
                          
                          function isInteger(s){
                              var i;
                              for (i = 0; i < s.length; i++){   
                                  // Check that current character is number.
                                  var c = s.charAt(i);
                                  if (((c < "0") || (c > "9"))) return false;
                              }
                              // All characters are numbers.
                              return true;
                          }
                          
                          function stripCharsInBag(s, bag){
                              var i;
                              var returnString = "";
                              // Search through string's characters one by one.
                              // If character is not in bag, append to returnString.
                              for (i = 0; i < s.length; i++){   
                                  var c = s.charAt(i);
                                  if (bag.indexOf(c) == -1) returnString += c;
                              }
                              return returnString;
                          }
                          
                          function daysInFebruary (year){
                              // February has 29 days in any year evenly divisible by four,
                              // EXCEPT for centurial years which are not also divisible by 400.
                              return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
                          }
                          function DaysArray(n) {
                              for (var i = 1; i <= n; i++) {
                                  this[i] = 31
                                  if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
                                  if (i==2) {this[i] = 29}
                             } 
                             return this
                          }
                          
                          function isDate(dtStr){
                              var daysInMonth = DaysArray(12)
                              var pos1=dtStr.indexOf(dtCh)
                              var pos2=dtStr.indexOf(dtCh,pos1+1)
                              var strDay=dtStr.substring(0,pos1)
                              var strMonth=dtStr.substring(pos1+1,pos2)
                              var strYear=dtStr.substring(pos2+1)
                              strYr=strYear
                              if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
                              if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
                              for (var i = 1; i <= 3; i++) {
                                  if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
                              }
                              month=parseInt(strMonth)
                              day=parseInt(strDay)
                              year=parseInt(strYr)
                              if (pos1==-1 || pos2==-1){
                                  alert("The date format should be : dd/mm/yyyy")
                                  return false
                              }
                              if (strMonth.length<1 || month<1 || month>12){
                                  alert("Please enter a valid month")
                                  return false
                              }
                              if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
                                  alert("Please enter a valid day")
                                  return false
                              }
                              if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
                                  alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
                                  return false
                              }
                              if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
                                  alert("Please enter a valid date")
                                  return false
                              }
                          return true
                          }
                          
                          function ValidateForm(){
                              var dt=document.frmSample.txtDateenter code here
                              if (isDate(dt.value)==false){
                                  dt.focus()
                                  return false
                              }
                              return true
                           }
                          
                          </script>
                          

                          【讨论】:

                            猜你喜欢
                            • 2016-01-26
                            • 2022-11-29
                            • 2014-01-18
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2011-09-04
                            • 2017-04-07
                            • 2016-01-02
                            相关资源
                            最近更新 更多