Valid Date //JavaScript Repository

Description

Date validation.
Created: 2006.04.25

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/geral/is-date [rev. #1]

isDate = function(y, m, d){
        if(typeof y == "string" && m instanceof RegExp && d){
            if(!m.test(y)) return 1;
            y = RegExp["$" + d.y], m = RegExp["$" + d.m], d = RegExp["$" + d.d];
        }
        d = Math.abs(d) || 0, m = Math.abs(m) || 0, y = Math.abs(y) || 0;
        return arguments.length != 3 ? 1 : d < 1 || d > 31 ? 2 : m < 1 || m > 12 ? 3 : /4|6|9|11/.test(m) && d == 31 ? 4
        : m == 2 && (d > ((y = !(y % 4) && (y % 1e2) || !(y % 4e2)) ? 29 : 28)) ? 5 + !!y : 0;
};

/*
Simple way, but without warnings
isDate = function(y, m, d){
    var o = new Date(y, --m, d);
    return o.getFullYear() == y && o.getMonth() == m && o.getDate() == d;
}
*/

Example (Example)

<script type="text/javascript">
//<![CDATA[

function getMessage(r){
    return r == 0 ? "Valid date"
    : r == 1 ? "Invalid date format"
    : r == 2 ? "Invalid day"
    : r == 3 ? "Invalid month"
    : r == 4 ? "In April, June, September and November the month has only 30 days"
    : r == 5 ? "February has only 28 days"
    : r == 6 && "It's leap year, February has only 29 days";
};

var tests = [
    isDate("22/07/1984", /^([0-9]{1,2})[\/]([0-9]{1,2})[\/]([0-9]{1,4})$/, {d: 1, m: 2, y: 3}),
    isDate("1984-07-22", /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/, {d: 3, m: 2, y: 1}),
    isDate("07-22-1984", /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/, {d: 3, m: 2, y: 1}),
    isDate(2000, 1, 32),
    isDate(2000, 0, 1),
    isDate(2000, 4, 31),
    isDate(2001, 2, 29),
    isDate(2004, 2, 30)
];

for(var i = -1, l = tests.length; ++i < l;)
    document.write(getMessage(tests[i]), "<br>");

//]]>
</script>

Help

isDate(y: Integer, m: Integer, d: Integer): Integer
Checks a date and returns 0 if it's valid or one of the error codes bellow.
y
year
m
month
d
day
isDate(date: String, matcher: RegExp, map: Object): Integer
Checks a date and returns 0 if it's valid or one of the error codes bellow.
date
date in a string form
matcher
regular expression responsible to find and store the day, month and year
map
object containing the position where each date component is localized inside the regular expression. Its format is the following: {d: positionOfTheDay, m: positionOfTheMonth, y: positionOfTheYear}

Return codes

  • 0 = Valid date
  • 1 = Date format invalid (regular expression failed or amount of arguments != 3)
  • 2 = Day isn't between 1 and 31
  • 3 = Month isn't between 1 and 12
  • 4 = On April, June, September and November there isn't the day 31
  • 5 = On February the month has only 28 days
  • 6 = Leap year, February has only 29 days

Rank (Votes: 37)

3.81