简体   繁体   English

JavaScript日期验证

[英]Javascript Date Validation

How to validate particular format date string using Javascript? 如何使用JavaScript验证特定格式的日期字符串? I have one date picker which has the display format like "dddd MMMM dd, yyyy"(displaying like this:"Wednesday February 03, 2010".) So i have to validate this format using javascript. 我有一个日期选择器,其显示格式为“ dddd MMMM dd,yyyy”(显示如下:“ Wednesday February 03,2010”。)因此,我必须使用JavaScript验证此格式。 Please help me for implementing this.. 请帮助我实施此操作。

If you want to check exactly that format, you could use regular expression: 如果要精确检查该格式,可以使用正则表达式:

var re = new RegExp( '^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\\s*(January|February|March|April|May|June|July|August|September|November|December)\\s*(\\d\\d),\\s*(\\d{2,4})$' );

var date = 'Wednesday February 03, 2010';
if ( ( match = date.match( re ) ) != null )
{ // valid
    alert( match );
}

Or if you just need to know if it is a valid date, what format ever, simply convert it: 或者,如果您只需要知道它是一个有效的日期,可以使用哪种格式,只需将其转换为:

var dateSec, dateObj, dateStr = 'Wednesday February 03, 2010';
dateSec = Date.parse( dateStr ); // unix timestamp
if ( dateSec ) // not NaN
   dateObj = new Date( dateSec ); // date object

If your application is going to require date manipulation methods, you may want to consider using something like the Datejs library. 如果您的应用程序需要日期处理方法,则可能要考虑使用类似Datejs库的方法。

If you opt for Datejs, you can use the parseExact() method for the validation. 如果选择Datejs,则可以使用parseExact()方法进行验证。 It will return a date object if the date is valid, or null if the date is invalid. 如果日期有效,它将返回一个日期对象;如果日期无效,则返回null。

Native JavaScript support for date formatting and validation is somewhat limited. 本地JavaScript对日期格式和验证的支持受到一定限制。

Take a look at http://www.datejs.com/ 看看http://www.datejs.com/

You can do stuff like Date.parse('my date string') 您可以执行类似Date.parse('my date string')的操作

Datejs or Dojo can do this. Datejs或Dojo可以做到这一点。 With dojo.date.locale.parse : 使用dojo.date.locale.parse

var dateAsString = "Wednesday February 03, 2010";
var dateObject = dojo.date.locale.parse(dateAsString, {datePattern: "EEEE MMMM dd, yyyy", selector: "date", locale: "en"});

dateObject will contain the Date object, or null if the string does not match the specified pattern. dateObject将包含Date对象;如果字符串与指定的模式不匹配,则为null。 This can work with a fixed language or any native language. 这可以与固定语言或任何本地语言一起使用。

It doesn't seem right that a date picker would use this as a serialized Date format, though. 但是,日期选择器将其用作序列化的Date格式似乎并不正确。 It should use something easier to parse, like ISO8601 representation . 它应该使用易于解析的内容,例如ISO8601表示形式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM