In this article I will explain with an example, how to implement Date of Birth (Age) Validation using Regular Expressions (Regex) in JavaScript.
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 following HTML Markup consists of an HTML TextBox, a SPAN element and a Button. The ValidateDOB JavaScript function is called on TextBox OnBlur event and on Button OnClick event.
<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()" />
Date of Birth (Age) Validation in JavaScript
The entered date is fetched from the TextBox and is tested with the dd//MM/yyyy Date Format Regular Expression (Regex).
Once the date is verified, the date is split and converted into a JavaScript Date object.
The converted JavaScript object i.e. the Date of Birth is compared with the Current Date to verify whether the Age meets the minimum Age criteria i.e. 18 years or higher.
<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
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads