There will be two types of Validations:
1. Date format dd/MM/yyyy validation: The Date of Birth (DOB) will be first validated for dd/MM/yyyy format using
Regular Expression (Regex).
2. 18+ Minimum Age validation: The difference between the age entered in the TextBox and the Current Date is minimum 18 years.
HTML Markup
The HTML Markup consists of following elements:
TextBox – For capturing the date.
The
TextBox has been assigned with a
JavaScript onblur function.
SPAN – For displaying error message.
Button – For validating the date in the TextBox.
The
Button has been has been assigned with a
JavaScript onclick function.
<input type="text" id="txtDate" onblur="ValidateDOB()" />
<span class="error" id="lblError"></span>
<br /><br />
<input type="button" id="btnValidate" value="Validate" onclick="return ValidateDOB()" />
Validating Date of Birth and 18+ Minimum Age in dd/MM/yyyy format using JavaScript
When the
Submit Button is clicked, the
ValidateDOB JavaScript function is executed.
Inside the
ValidateDOB JavaScript function, the entered date is fetched from the
TextBox and referenced and its value is tested using a
Regular Expression.
If test result is succeeded then, a check is performed if the user is eighteen years old or not by comparing current date and birth date.
If the Age is less than 18 then it will return FALSE and SPAN for displaying Error Message is set to empty.
If the entered date is not in dd/MM/yyyy format then, the Error Message is displayed.
<script type="text/javascript">
function ValidateDOB() {
var lblError = document.getElementById("lblError");
//Get the date from the TextBox.
var dateString = document.getElementById("txtDate").value;
var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;
//Check whether valid dd/MM/yyyy Date Format.
if (regex.test(dateString)) {
var parts = dateString.split("/");
var dtDOB = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
var dtCurrent = new Date();
lblError.innerHTML = "Eligibility 18 years ONLY."
if (dtCurrent.getFullYear() - dtDOB.getFullYear() < 18) {
return false;
}
if (dtCurrent.getFullYear() - dtDOB.getFullYear() == 18) {
//CD: 11/06/2018 and DB: 15/07/2000. Will turned 18 on 15/07/2018.
if (dtCurrent.getMonth() < dtDOB.getMonth()) {
return false;
}
if (dtCurrent.getMonth() == dtDOB.getMonth()) {
//CD: 11/06/2018 and DB: 15/06/2000. Will turned 18 on 15/06/2018.
if (dtCurrent.getDate() < dtDOB.getDate()) {
return false;
}
}
}
lblError.innerHTML = "";
return true;
} else {
lblError.innerHTML = "Enter date in dd/MM/yyyy format ONLY."
return false;
}
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads