Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

jquery - JavaScript Detecting Valid Dates

Possible Duplicate:
Detecting an “invalid date” Date instance in JavaScript

I was using the following to detect a valid date:

var text = $('#Date').val();
var date = Date.parse(text);

if (isNaN(date)) {
      // Invalid date
}

But found that Date.parse thinks the following are valid dates (mm/dd/yyyy)

  • 2/30/2011
  • 11/31/2011

Any other way to detect invalid dates when the number of days surpasses the total number of days in the month?

UPDATE: An even larger problem is that the jQuery validation plugin doesn't detect this as an invalid date either!

SOLUTION:

Based on @Guffa's comments I have created the following function to validate dates:

function validDate(text) {

    var date = Date.parse(text);

    if (isNaN(date)) {
        return false;
    }

    var comp = text.split('/');

    if (comp.length !== 3) {
        return false;
    }

    var m = parseInt(comp[0], 10);
    var d = parseInt(comp[1], 10);
    var y = parseInt(comp[2], 10);
    var date = new Date(y, m - 1, d);
    return (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To check if a date is valid you can parse the components of the date, create a Date object from it, and check if the components in the data is the same as the parsed components. If you create a Date object from compnents that are out of range, the values will flow over to the next/previous period to create a valid date.

For example, new Date(2011,0,42) will create an object that contains the date 2/11/2011 instead of 1/42/2011.

By parsing the components instead of the full date you will also get around the problem with different date formats. My browser will for example expect a date format like y-m-d rather than d/m/y.

Example:

var text = '2/30/2011';
var comp = text.split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y,m-1,d);
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
  alert('Valid date');
} else {
  alert('Invalid date');
}

Demo: http://jsfiddle.net/Guffa/UeQAK/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...