Validate a date effectively with any delimiter and 4 digit year
/* Validate a date from string effectively with
* any delimiter and 4 digit year.
* @param value The value of the input.
* @param userFormat The user format with 4 digit year.
* @return bool
*/
function isValidDate (value, userFormat) {
userFormat = userFormat || 'mm/dd/yyyy'
var delimiter = /[^mdy]/.exec(userFormat)[0]
var theFormat = userFormat.split(delimiter)
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 && d <= (new Date(y, m, 0)).getDate()
)
}
return isDate(theDate, theFormat)
}
// Usage:
// This will return FALSE,
// November doesn't have 31 days
console.log( isValidDate('dd/mm/yyyy', '31/11/2012') )
Written by Cedric Ruiz
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Validation
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#