【问题标题】:Javascript - Regex to validate date format [duplicate]Javascript - 正则表达式验证日期格式
【发布时间】:2011-09-12 12:39:11
【问题描述】:

有没有办法在 JavaScript 中使用正则表达式来验证多种格式的日期,例如:DD-MM-YYYY 或 DD.MM.YYYY 或 DD/MM/YYYY 等?我需要所有这些都在一个正则表达式中,但我不太擅长。到目前为止,我想出了这个:var dateReg = /^\d{2}-\d{2}-\d{4}$/; 代表 DD-MM-YYYY。我只需要验证日期格式,而不是日期本身。

【问题讨论】:

  • 您可能对datejs.com感兴趣
  • 如果唯一不同的是分隔符,则将 - 替换为 [\-\/\.](或任何转义)。
  • 这是您自己的自定义格式日期字符串。国际格式为:dd.mm.yyyy 或 mm/dd/yyyy 或 yyyy-mm-dd。
  • 这是最好的答案,没有丑陋的正则表达式之类的:stackoverflow.com/questions/5774931/…
  • @EduardLuca 好的,谢谢!只是想让事情对后来提出问题的其他人更有帮助;)干杯!

标签: javascript regex


【解决方案1】:

您可以使用字符类 ([./-]),以便分隔符可以是任何已定义的字符

var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/

或者更好的是,匹配第一个分隔符的字符类,然后将其捕获为一个组 ([./-]) 并使用对捕获的组 \1 的引用来匹配第二个分隔符,这将确保两个分隔符都是一样的:

var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/

"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches

【讨论】:

  • 谢谢。除了斜线“/”没有正确转义之外,它工作正常。
  • 我不认为斜线需要在字符类中转义,但是如果你想转义它也没有什么坏处。可能会使文本编辑器中的语法高亮显示效果更好,但无论哪种方式都应该有效。
  • 你能添加一个限制,让第一个数字(月份)不超过'3'吗?
  • 试试var dateReg = /^0[123]([./-])\d{2}\1\d{4}$/
  • 或者您可以使用npmjs.com/package/raysk-vali 进行日期验证等。
【解决方案2】:

格式、日、月、年:

var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;

【讨论】:

  • 这部分验证了日期,但仍然允许像 30-02-2013 这样无效的日期。需要更复杂的规则来考虑不同的月份长度。
  • 从技术上讲@BillyMoon,我们实际上是在验证它的格式,而不是日期本身。你的也允许像 30-02-2013 这样的日期,我的朋友。
  • 是的,我的设计用于从有效日期中提取数字,并且不会尝试进行验证,而您的则这样做。我认为通过一些调整,你可以对日期进行合理的验证,我希望看到你这样做,但在我看来,对它们进行一半的验证就像在悬崖边上有一道薄弱的栅栏,最好根本没有,以免有人倾斜在上面!最好还是有一个强大的。
  • @BillyMoon Format, days, months and year:,你在说什么?
  • @Dropout - 你的问题是针对@nicoabie 的吗?
【解决方案3】:

建议的正则表达式不会验证日期,只会验证模式。

所以 99.99.9999 将通过正则表达式。

您后来指定只需要验证模式,但我仍然认为创建日期对象更有用

function isDate(str) {    
  var parms = str.split(/[\.\-\/]/);
  var yyyy = parseInt(parms[2],10);
  var mm   = parseInt(parms[1],10);
  var dd   = parseInt(parms[0],10);
  var date = new Date(yyyy,mm-1,dd,0,0,0,0);
  return mm === (date.getMonth()+1) && dd === date.getDate() && yyyy === date.getFullYear();
}
var dates = [
    "13-09-2011", 
    "13.09.2011",
    "13/09/2011",
    "08-08-1991",
    "29/02/2011"
]

for (var i=0;i<dates.length;i++) {
    console.log(dates[i]+':'+isDate(dates[i]));
}    

【讨论】:

  • 无效日期值的验证将由我手动完成。如果我在您的解决方案中输入 08-08-1991 之类的内容,由于某种原因,我会在 javascript 中得到一个“无效日期”。
  • 不在 Fx 中:我将该日期添加到 jsfiddle.net/mplungjan/Mqh8D 你是什么浏览器?
  • 如果你使用 parseInt 你必须使用基数 10 因为 08 和 09 是无效的八进制数
【解决方案4】:

您可以通过使用 OR (|) 运算符来使用正则多个表达式。

function validateDate(date){
    var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
    var dateOk=regex.test(date);
    if(dateOk){
        alert("Ok");
    }else{
        alert("not Ok");
    }
}

以上函数可以验证YYYY-MM-DD、DD-MM-YYYY日期格式。您可以简单地扩展正则表达式来验证任何日期格式。假设您要验证 YYYY/MM/DD,只需将“[-]”替换为“[-|/]”。此表达式可以验证日期为 31,月份为 12。但闰年和以 30 天结尾的月份未验证。

【讨论】:

    【解决方案5】:

    【讨论】:

    • 我会投票给你,因为你给了我一个更简洁的版本
    【解决方案6】:

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

    【讨论】:

      【解决方案7】:

      试试这个:

      ^\d\d[./-]\d\d[./-]\d\d\d\d$
      

      【讨论】:

        【解决方案8】:

        不要重新发明轮子。使用预构建的解决方案来解析日期,例如 http://www.datejs.com/

        【讨论】:

        • 我不想添加外部库的原因是没有必要,它只会使网站加载速度变慢。但是,是的,那将是一个解决方案
        【解决方案9】:

        @mplungjan,@eduard-luca

        function isDate(str) {    
            var parms = str.split(/[\.\-\/]/);
            var yyyy = parseInt(parms[2],10);
            var mm   = parseInt(parms[1],10);
            var dd   = parseInt(parms[0],10);
            var date = new Date(yyyy,mm-1,dd,12,0,0,0);
            return mm === (date.getMonth()+1) && 
                dd === date.getDate() && 
                yyyy === date.getFullYear();
        }
        

        new Date() 使用当地时间,00:00:00 小时将显示我们有“夏令时”或“DST(夏令时)”事件的最后一天。

        例子:

        new Date(2010,9,17)
        Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)
        

        另一种方法是使用 getUTCDate()。

        【讨论】:

          【解决方案10】:

          为确保它能够正常工作,您需要对其进行验证。

          function mmIsDate(str) {
          
              if (str == undefined) { return false; }
          
              var parms = str.split(/[\.\-\/]/);
          
              var yyyy = parseInt(parms[2], 10);
          
              if (yyyy < 1900) { return false; }
          
              var mm = parseInt(parms[1], 10);
              if (mm < 1 || mm > 12) { return false; }
          
              var dd = parseInt(parms[0], 10);
              if (dd < 1 || dd > 31) { return false; }
          
              var dateCheck = new Date(yyyy, mm - 1, dd);
              return (dateCheck.getDate() === dd && (dateCheck.getMonth() === mm - 1) && dateCheck.getFullYear() === yyyy);
          
          };
          

          【讨论】:

            【解决方案11】:

            如果您想验证您的 date(YYYY-MM-DD) 以及比较,它将完全为您使用...

                function validateDate()
                {
                 var newDate = new Date();
                 var presentDate = newDate.getDate();
                 var presentMonth = newDate.getMonth();
                 var presentYear = newDate.getFullYear();
                 var dateOfBirthVal = document.forms[0].dateOfBirth.value;
                if (dateOfBirthVal == null) 
                return false;
                var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
                dateValues = dateOfBirthVal.match(validatePattern);
                if (dateValues == null) 
                {
                    alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
                return false;
                    }
                var birthYear = dateValues[1];        
                birthMonth = dateValues[3];
                birthDate=  dateValues[5];
                if ((birthMonth < 1) || (birthMonth > 12)) 
                {
                    alert("Invalid date")
                return false;
                    }
                else if ((birthDate < 1) || (birthDate> 31)) 
                {
                    alert("Invalid date")
                return false;
                    }
                else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31) 
                {
                    alert("Invalid date")
                return false;
                    }
                else if (birthMonth == 2){ 
                var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
                if (birthDate> 29 || (birthDate ==29 && !isleap)) 
                {
                    alert("Invalid date")
                return false;
                    }
                }
                else if((birthYear>presentYear)||(birthYear+70<presentYear))
                    {
                    alert("Invalid date")
                    return false;
                    }
                else if(birthYear==presentYear)
                    {
                    if(birthMonth>presentMonth+1)
                        {
                        alert("Invalid date")
                        return false;
                        }
                    else if(birthMonth==presentMonth+1)
                        {
                        if(birthDate>presentDate)
                            {
                            alert("Invalid date")
                            return false;
                            }
                        }
                    }
            return true;
                }
            

            【讨论】:

              猜你喜欢
              • 2014-03-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-12-31
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-05-03
              相关资源
              最近更新 更多