In my first steps in ASP.NET Core MVC; I am trying to perform a validation of the date of birth field with jQuery validation since the data annotations does not allow it or I do not know how to do it.
The validation consists in the first part of the user selecting a different date to today's date and at least select a date 5 years ago to later validate the age based on the date by performing a calculation, as seen in the image is what I would like to do, the question is how to do it based on the code that I maintain.
<script>
$(document).ready(function() {
$('#formPaciente').validate({
rules: {
txtFecNac: "required",
txtEdad: {
required: true,
Range:[5,90]
}
},
messages: {
txtFecNac: "La Fecha Nacimiento es requerida",
txtEdad: {
required: "Su edad es requerida",
Range: "La edad debe ser entre 5 y 90"
}
},
});
});
</script>
But my qiestions are like first how to calculate the age based on the date of birth using jQuery validation and second is to be able to validate that the date of birth at least based on the calculation of the age I am 5 years old with which I would fill a additional field called representative and if it is greater then I normally continue with the next field, which would be the correct way to carry out this validation.
I appreciate your help
Add this attribute to the date input [email protected](-5).ToString("yyyy-MM-dd")
Just like this:
<div class="form-group">
<label asp-for="birthday" class="control-label"></label>
<input asp-for="birthday" class="form-control" [email protected](-5).ToString("yyyy-MM-dd")/>
<span asp-validation-for="birthday" class="text-danger"></span>
</div>
And the result looks like below, no need to validate again.
And to calculate the age, just add an Onchange event for the date input and according to the birth date user clicked, update the age input.
$("#tarDate").on("change", function () {
var now = new Date();
var birthdate = new Date($("#tarDate").val());
var nowyear = now.getFullYear();
var birthyear = birthdate.getFullYear();
var age = nowyear - birthyear + 1;
$('#age').val(age);
});