-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate-validation.js
39 lines (32 loc) · 1.04 KB
/
date-validation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function isValidDate(value, userFormat) {
// Set default format if format is not provided
userFormat = userFormat || 'mm/dd/yyyy';
// Find custom delimiter by excluding
// month, day and year characters
var delimiter = /[^mdy]/.exec(userFormat)[0];
// Create an array with month, day and year
// so we know the format order by index
var theFormat = userFormat.split(delimiter);
// Create array from user date
var theDate = value.split(delimiter);
function isDate(date, format) {
var m, d, y, i = 0, len = format.length, f;
for (i; i < len; i++) {
f = format[i];
if (/m/.test(f)) m = date[i];
if (/d/.test(f)) d = date[i];
if (/y/.test(f)) y = date[i];
}
return (
m > 0 && m < 13 &&
y && y.length === 4 &&
d > 0 &&
// Check if it's a valid day of the month
d <= (new Date(y, m, 0)).getDate()
);
}
return isDate(theDate, theFormat);
}
/*Usage:
The following will return false because November doesn’t have 31 days.
isValidDate('dd-mm-yyyy', '31/11/2012')*/