Given a string str
, how could I check if it is in the dd/mm/yyyy
format and contains a legal date ?
Some examples:
bla bla
Try -
var strDate = '12/03/2011';
var dateParts = strDate.split("/");
var date = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0]);
There's more info in this question - Parse DateTime string in JavaScript (the code in my answer is heavily influenced by linked question)
Demo - http://jsfiddle.net/xW2p8/
EDIT
Updated answer, try -
function isValidDate(strDate) {
if (strDate.length != 10) return false;
var dateParts = strDate.split("/");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
if (date.getDate() == dateParts[0] && date.getMonth() == (dateParts[1] - 1) && date.getFullYear() == dateParts[2]) {
return true;
}
else return false;
}
This function passes all the test cases. As far as I'm aware, Adam Jurczyk had posted an accurate answer well before I corrected my original wrong answer. He deserves credit for this.
Demo - http://jsfiddle.net/2r6eX/1/