开发者

Javascript Date Validation

开发者 https://www.devze.com 2022-12-19 05:03 出处:网络
How to validate particular format date string using Javascript? I have one date picker which has the display format like \"dddd MMMM 开发者_StackOverflow社区dd, yyyy\"(displaying like this:\"Wednesda

How to validate particular format date string using Javascript? I have one date picker which has the display format like "dddd MMMM 开发者_StackOverflow社区dd, yyyy"(displaying like this:"Wednesday February 03, 2010".) So i have to validate this format using 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.

If you opt for Datejs, you can use the parseExact() method for the validation. It will return a date object if the date is valid, or null if the date is invalid.


Native JavaScript support for date formatting and validation is somewhat limited.

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

You can do stuff like Date.parse('my date string')


Datejs or Dojo can do this. With 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. 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. It should use something easier to parse, like ISO8601 representation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号