Skip to content

Instantly share code, notes, and snippets.

@sampathsl sampathsl/check-date.js
Last active Oct 18, 2016

Embed
What would you like to do?
Validate the user entered date using JavaScript
/*
* Validate the user entered date
* '01/01/1970' -> valid date
* '45/01/1970' -> invalid date
*/
function checkDate(str)
{
var date = null;
var matches = str.match(/(\d{1,2})[\/](\d{1,2})[\/](\d{4})/);
if (!matches) return;
var day = parseInt(matches[1],10);
var month = parseInt(matches[2],10);
var year = parseInt(matches[3],10);
date = new Date(year, month - 1, day);
var calcDay = date.getDate();
var calcMonth = date.getMonth();
var calcYear = date.getFullYear();
if (calcDay != day || calcMonth != (month - 1) || calcYear != year) {
return;
}
return date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.