[英]Validating Date with Regex
I need a regex to pattern match the following - 我需要一个正则表达式来匹配以下内容-
mm/dd/yyyy
The following date entries should pass validation: 以下日期条目应通过验证:
Also, after validating above regex
, what is the best way convert above date string
to Date
object? 另外,在验证上述
regex
,将上述日期string
转换为Date
对象的最佳方法是什么?
You should do the check and the parsing in one go, using split, parseInt and the Date constructor : 您应该使用split,parseInt和Date构造函数一次性进行检查和解析:
function toDate(s) {
var t = s.split('/');
try {
if (t.length!=3) return null;
var d = parseInt(t[1],10);
var m = parseInt(t[0],10);
var y = parseInt(t[2],10);
if (d>0 && d<32 && m>0 && m<13) return new Date(y, m-1, d);
} catch (e){}
}
var date = toDate(somestring);
if (date) // ok
else // not ok
01/22/2012 ==> Sun Jan 22 2012 00:00:00 GMT+0100 (CET)
07/5/1972 ==> Wed Jul 05 1972 00:00:00 GMT+0100 (CEST)
999/99/1972 ==> invalid
As other answers of this page, this wouldn't choke for 31 in February. 作为此页面的其他答案,2月份不会有31个。 That's why for all serious purposes you should instead use a library like Datejs .
因此,出于所有重要目的,您应该改用Datejs之类的库。
"/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/"
var dateStr = '01/01/1901',
dateObj = null,
dateReg = /^(?:0[1-9]|1[012]|[1-9])\/(?:[012][1-9]|3[01]|[1-9])\/(?:19|20)\d\d$/;
// 01 to 12 or 1 to 9 / 01 to 31 or 1 to 9 / 1900 to 2099
if( dateStr.match( dateReg ) ){
dateObj = new Date( dateStr ); // this will be in the local timezone
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.