问题
I found a lot of links to validate string if it is a date.
Like here and here.
But anyway I cannot figure out how to validate if we have this thing:
6/6/2012 where first 6 is month and the second 6 is days
and also if user input it like that:
06/06/2012
Any clue how it could be done in a proper way?
Thanks!!
回答1:
Here, this should work with any date format with 4 digit year and any delimiter. I extracted it from my plugin Ideal Forms which validates dates and much more.
var isValidDate = function (value, userFormat) {
var
userFormat = userFormat || 'mm/dd/yyyy', // default format
delimiter = /[^mdy]/.exec(userFormat)[0],
theFormat = userFormat.split(delimiter),
theDate = value.split(delimiter),
isDate = function (date, format) {
var m, d, y
for (var i = 0, len = format.length; i < len; i++) {
if (/m/.test(format[i])) m = date[i]
if (/d/.test(format[i])) d = date[i]
if (/y/.test(format[i])) 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)
}
回答2:
Use a regular expression.
var dateRegEx = /^(0[1-9]|1[012]|[1-9])[- /.](0[1-9]|[12][0-9]|3[01]|[1-9])[- /.](19|20)\d\d$/
console.log("06/06/2012".match(dateRegEx) !== null) // true
console.log("6/6/2012".match(dateRegEx) !== null) // true
console.log("6/30/2012".match(dateRegEx) !== null) // true
console.log("30/06/2012".match(dateRegEx) !== null) // false
Learn about RegEx.
Edit - A Disclaimer
As @elclanrs pointed out, this only validates the string's format, and not the actual date, which means that dates like February 31st would pass. However, since the OP only asks "to validate date string format," I'll keep this answer here because for some, it might be all you need.
As a note, the jQuery Validation plugin that the OP was using, also only validates format.
Finally, for those wondering, if you needed to validate the date, and not just the format, this regular expression would have ~2% rate of failure over the domain of (1-12)/(1-31)/(1900-2099) date strings. Please don't use this in Mission Critical code for JPL.
来源:https://stackoverflow.com/questions/11218181/best-way-to-validate-date-string-format-via-jquery