【问题标题】:Regex validate date years in range正则表达式验证范围内的日期年份
【发布时间】:2014-04-29 20:15:40
【问题描述】:

我需要使用正则表达式验证 1600 到 9999 之间的日期年份。有人知道最好的方法吗?例如使用这个给定的格式dd/mm/yyyy

【问题讨论】:

  • 你真的需要使用正则表达式吗?
  • 用正则表达式?如何?为什么?
  • 虽然可以使用正则表达式来验证日期,但它是不必要的复杂和麻烦。除非您确实必须使用正则表达式,否则请使用其他方法验证您的输入。
  • 我创建了这个 javascript 库来验证年份范围:github.com/jonschlinkert/is-valid-year

标签: javascript regex validation date range


【解决方案1】:

假设您可以信任该格式,最简单的方法是拆分 / 并检查年份是否在此范围内。

var year = date.split("/").pop();
valid = year >= 1600 && year <= 9999

如果您使用正则表达式:

/\d\d\/\d\d\/(1[6-9]\d\d|[2-9]\d\d\d)/

可能是你所追求的。

如果您需要更复杂的日期解析,您应该使用 moment.js 之类的东西

var year = moment(date, "DD/MM/YYYY").year();

【讨论】:

  • 我的错误,直到现在我才注意到标题指定它们仅在验证年份之后。
【解决方案2】:

如果您使用 Javascript,只需将值作为字符串,然后将其推送到 Date() 对象中。不需要正则表达式。

date = new Date("24/12/2014") //Valid date
date = new Date("40/10/2014") //Invalid date

//Detect whether date is valid or not:
if( !isNan( date.valueOf() ) ) {    //You can also use date.getTime() instead
    //Valid Date
} else {
    //Invalid Date
}

从这里,您可以根据您的需要提取date 对象,例如date.getMonth()。享受吧!

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

【讨论】:

    【解决方案3】:

    不要为此使用正则表达式,请尝试以下功能:

    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[0], 10);
        var month = parseInt(parts[1], 10);
        var year = parseInt(parts[2], 10);
    
        // Check the ranges of month and year
        if(year < 1600 || year > 9999 || 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];
    };
    

    工作示例:

    http://jsfiddle.net/tuga/8rj6Q/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-22
      • 2017-10-31
      • 2017-10-06
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多