JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head><meta charset=utf-8 />
<body>
JavaScript
function isValidDateA ( s ) {
var bits = s.split('/');
if ( s.indexOf(' ') != -1 ) {
//White space exists in the original date string
return false;
}
//Javascript month starts at zero
var d = new Date(bits[2], bits[0] - 1, bits[1]);
if ( isNaN( Number(bits[2]) ) ) {
//Year is not valid number
return false;
}
if ( Number(bits[2]) < 1 ) {
//Year should be greater than zero
return false;
}
//1. Check whether the year is a Number
//2. Check whether the date parts are eqaul to original date components
//3. Check whether d is valid
return d && ( (d.getMonth() + 1) == bits[0]) && (d.getDate() == Number(bits[1]) );
}
function isValidDateB ( str ) {
// parse to numbers
var rm = str.split( '/' )
, m = 1 * rm[0]
, d = 1 * rm[1]
, y = 1 * rm[2]
;
if ( isNaN( m * d * y ) ) { return false; }
if ( d < 1 ) { return false; } // day can't be 0
if ( m < 1 || m > 12 ) { return false; } // month must be 1-12
if ( m === 2 ) { // february
var is_leap_year = ((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0);
if ( is_leap_year && d > 29 ) { return false; } // leap year
if ( !is_leap_year && d > 28 ) { return false; } // non-leap year
}
// test any other month
else if ((( m === 4 || m === 6 || m === 9 || m === 11 ) && d > 30) ||
(( m === 1 || m === 3 || m === 5 || m === 7 || m === 8 || m === 10 || m === 12 ) && d > 31)) {
return false;
}
return true;
}
function print ( str ) {
document.body.innerHTML += (str||'') + '<br>';
}
function test ( str ) {
print( str + ': ' + isValidDateA(str) + ', ' + isValidDateB(str) );
}
test('12/33/2012');
test('12/12/2012');
test('2/29/2012');
test('2/ 29 /2012');
test('02/29/2013');
test('12/33/2012');
test('12/12/2012');
test('02/29/2012');
test('02/29/2013');
test('01/01/2013A');
test('10/10/-50');
test('10/10/45');