用于测试日期格式的正则表达式 [英] Regex for testing date formatting

查看:126
本文介绍了用于测试日期格式的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个非常有用的正则表达式,用于测试正则表达式示例站点中日期字段的格式和内容

I found a very useful regular expression for testing format and content of a date field in a regex example site

但是,当我输入的日期早于2000年时,我会得到验证,并且由于这是输入出生日期的字段,因此您可以了解为什么会出现问题.我相信这很容易解决,但是正则表达式会吓倒我.

BUT I get a validation when I put in dates older than 2000 and since this is a field for inputting date of birth you can see why it would be a problem. I am sure it is an easy fix but regular expressions intimidate me.

$('#txtDOB').blur(function() {
//$('span.error-keyup-5').remove();
var inputVal = $(this).val();
var dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
if(!dateReg.test(inputVal)) {
    alert('invalid date format: ' + inputVal);
}

我不喜欢这种解决方案,因此,如果您可以提出更好的方法,请发表评论.

I am not married to this solution so if you can suggest a better way please comment away.

推荐答案

我建议您询问JavaScript是否 it 认为这是有效日期:

Instead of testing if a string matches one or more formats that you think might be good dates, I would suggest instead asking JavaScript if it thinks it is a valid date:

function isValidDate(str){
  return !isNaN(new Date(str));
}

这假定您将接受用户以各种格式中的任何一种给您的内容(例如,恐怖的US MM/DD/YYYY或更健全的ISO8601 YYYY-MM-DD).相反,如果您只接受特定的格式,则根据该格式解析字符串,提取年/月/日,然后询问JavaScript这是否是有效日期:

This assumes that you're going to accept what the user gives you in any of a variety of formats (e.g. the horrid US MM/DD/YYYY or the more sane ISO8601 YYYY-MM-DD). If instead you have a specific format you will only accept, then parse your string based on that, pull out the year/month/date, and then ask JavaScript if this is a valid date:

function isValidDate(year, month, date) {
  var d = new Date(year*=1, month-=1, date*=1, 12);    // noon to skip DST issues
  return d.getFullYear()==year && d.getMonth()==month; // wrong date->wrong month
}

您需要检查年/月/日是否都匹配,因为new Date(2011,11,32)被接受并解释为2012-1-1.

You need to check that the year/month/date all match because new Date(2011,11,32) is accepted and interpreted as 2012-1-1.

另请参见:用于确保日期为有效

这篇关于用于测试日期格式的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆