I am using jQuery datepicker on a sign up form and am trying to validate a minimum age of 16.
I have used https://www.aspsnippets.com/Articles/Date-of-Birth-Age-validation-with-jQuery-DatePicker.aspx as a reference point.
HTML
<div class="col-12 mt-3 col-md-6 mt-md-0">
<label for="dateBirth" class="form-label">Date of Birth</label>
<input type="text" class="form-control datepicker" id="dateBirth" name="dateBirth" placeholder="dd/mm/yyyy" readonly>
</div>
JS
$(function() {
$('#dateBirth').datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1920:+0',
onSelect: function (dateString, dateBirth) {
ValidateDOB(dateString);
}
});
});
function ValidateDOB(dateString) {
console.log(dateString);
var parts = dateString.split("/");
console.log(parts);
var dtDOB = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
var dtCurrent = new Date();
if (dtCurrent.getFullYear() - dtDOB.getFullYear() < 16) {
return false;
}
if (dtCurrent.getFullYear() - dtDOB.getFullYear() == 16) {
if (dtCurrent.getMonth() < dtDOB.getMonth()) {
return false;
}
if (dtCurrent.getMonth() == dtDOB.getMonth()) {
if (dtCurrent.getDate() < dtDOB.getDate()) {
return false;
}
}
}
return true;
}
Validation
if(!ValidateDOB()) {
error.style.display = "block";
error.innerHTML = 'You must be at least 16 years of age to register as a panellist.';
dateBirth.classList.add("is-invalid");
return;
}
When I select a date, in my console it is outputting the date (i.e. 15/02/2023
) as well as the parts
variable (i.e. ["15", "02", "2023"]
) however when I submit the form to run the form validation, I get TypeError: undefined is not an object (evaluating 'dateString.split')
.
This would usually suggest to me that dateString is not returning anything, however the console log is proving it is. What could be wrong here?
2
Answers
I did away with the function and just split all the dates up in to parts, so run some validation by year, then by month if the year is equalled, then by day if the month is also equalled. Not the cleanest of solutions but it works well.
The issue is that in the validation part of your code, ValidateDOB() is called without passing any argument. In the ValidateDOB function definition, dateString is expected as an argument.
You should pass the selected date string to ValidateDOB function in the validation part of the code like this: