Created
December 3, 2015 22:16
-
-
Save edgarshurtado/52c2dd5ffc7ffe9abce6 to your computer and use it in GitHub Desktop.
Validación de fecha con JavaScript
This file contains 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
//------------------------------DATE CHECK------------------------------------- | |
// Returns if a given string date is valid. Months, days and years have the normal | |
// numeration starting from 1 | |
// Valid formats for the string date: dd-mm-yy / dd/mm/yy / dd mm yy | |
function checkDate(dateString){ | |
var dateStringParsed = parseDate(); | |
if(dateStringParsed === null){ | |
return false; | |
} | |
var day = dateStringParsed.day; | |
var month = parseInt(dateStringParsed.month); | |
month--; //Change the month to index | |
var year = dateStringParsed.year; | |
return isValidDate() && dateNotAhead(); | |
// Parse date string from input field | |
// Takes dateString as variable | |
function parseDate() { | |
var regEx = new RegExp("[-/\\s]", "g"); | |
dateString = dateString.replace(regEx, "/"); | |
dateString = dateString.split("/"); | |
if(dateString.length !== 3){ | |
return null; | |
} | |
return {day : dateString[0], | |
month : dateString[1], | |
year : dateString[2]}; | |
} | |
//Checks if day, month and year are a real date | |
function isValidDate(){ | |
var month_short_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', | |
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; | |
var dateString = month_short_names[month] + " " + | |
day.toString() + " " + | |
year.toString(); | |
console.log(dateString); | |
return !isNaN(Date.parse(dateString)); | |
} | |
//Checks that the introduced date (day, month and year variables) | |
//isn't ahead | |
function dateNotAhead(){ | |
var currentDateMs = Date.parse(new Date()); | |
var providedDateMs = Date.parse(new Date(year, month, day)); | |
return currentDateMs >= providedDateMs; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment