Last active
August 26, 2021 15:19
-
-
Save ace-racer/240f8b3f150a30c22c250793c0b024d3 to your computer and use it in GitHub Desktop.
Validate date in JavaScript (dd/mm/yyyy format)
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 validatedate() { | |
var dateText = document.getElementById("DATE_FIELD_NAME"); | |
if (dateText) { | |
try { | |
var errorMessage = ""; | |
var splitComponents = dateText.value.split('/'); | |
if (splitComponents.length > 0) { | |
var day = parseInt(splitComponents[0]); | |
var month = parseInt(splitComponents[1]); | |
var year = parseInt(splitComponents[2]); | |
if (isNaN(day) || isNaN(month) || isNaN(year)) { | |
errorMessage = "The day, month and year need to be numbers"; | |
alert(errorMessage); | |
return false; | |
} | |
if (day <= 0 || month <= 0 || year <= 0) { | |
errorMessage = "The day, month and year need to be positive values greater than 0"; | |
} | |
if (month > 12) { | |
errorMessage = "The month cannot be greater than 12."; | |
} | |
if (errorMessage == "") { | |
// assuming no leap year by default | |
var daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; | |
if (year % 4 == 0) { | |
// current year is a leap year | |
daysPerMonth[1] = 29; | |
} | |
if (day > daysPerMonth[month - 1]) { | |
errorMessage = "Number of days are more than those allowed for the month"; | |
} | |
} | |
} else { | |
errorMessage = "Please enter the date in dd/mm/yyyy format"; | |
} | |
if (errorMessage) { | |
alert(errorMessage); | |
return false; | |
} | |
} catch (e) { | |
alert(e); | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment