Created
December 20, 2012 22:10
-
-
Save dwoodard/4348994 to your computer and use it in GitHub Desktop.
Javascript: isValidDate()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isValidDate(value, userFormat) { | |
// Set default format if format is not provided | |
userFormat = userFormat || 'mm/dd/yyyy'; | |
// Find custom delimiter by excluding the | |
// month, day and year characters | |
var delimiter = /[^mdy]/.exec(userFormat)[0]; | |
// Create an array with month, day and year | |
// so we know the format by index | |
var theFormat = userFormat.split(delimiter); | |
// Get the user date now that we know the 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 && | |
// Is it a valid day of the month? | |
d <= (new Date(y, m, 0)).getDate() | |
); | |
} | |
return isDate(theDate, theFormat); | |
} | |
$('button').click(function(){ | |
$('span').text( | |
isValidDate( $('input').val() ) ? | |
'Congrats! It\'s a valid date' : | |
'Sorry, not a valid date.' | |
); | |
}); |
I propose an alternative implementation:
function isValidDate(value, userFormat) {
return "I don't know."
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like your usage of the regular expression to determine the delimiter. Elegant solution.