I would like to create a custom error message for an input of type date. The rules are, the input is required. If an input is provided, it should be in the range from 1-1-1920 to lastyear (today's date minus one year). I've done the following This is my input field:
<div class="form-group col-lg-5 desktop-margin">
<label for="DateofBirth" class="required-field">Date of birth</label>
<input id="dob" name="dob" type="date" class="form-control" value="@Model.DateofBirth" data-val="true" data-rule-required="true" data-val-required="Date of birth is required." data-rule-customdate="true" data-val-customdate="Invalid date.">
<div id="dobError" class="help-block field-validation-valid"></div>
</div>
and here is my jQuery:
$.validator.addMethod("customdate", function (value, element) {
// Convert the input value to a Date object
var selectedDate = new Date(value);
// Get today's date and calculate the date one year ago
var currentDate = new Date();
var oneYearAgo = new Date();
oneYearAgo.setFullYear(currentDate.getFullYear() - 1);
// Define the minimum and maximum allowed dates (1/1/1920 and today's date - 1 year)
var minDate = new Date("1920-01-01");
var maxDate = oneYearAgo;
console.log("selectedDate is: " + selectedDate + " minimum date is: " + minDate + " maximum date is: " + maxDate);
// Check the conditions and return the result
if (isNaN(selectedDate)) {
console.log("no date was provided");
createErrorSpan("Date of birth is required.");
return false; // Date is not valid
} else if (selectedDate > maxDate) {
console.log("date is big");
createErrorSpan("Date should occur before " + formatDate(maxDate) + ".");
return false; // Date is bigger than today's date - 1 year
} else if (selectedDate < minDate) {
console.log("date is small");
createErrorSpan("Date should occur after " + formatDate(minDate) + ".");
return false; // Date is less than 1/1/1920
}
return true; // Date is valid and meets all conditions
});
// Adapter for customdate validation method
$.validator.unobtrusive.adapters.add("customdate", function (options) {
options.rules["customdate"] = true;
options.messages["customdate"] = options.message;
});
$("#dob").on("input", function () {
var isValid = $("#MyForm").valid();
console.log("input is triggered and its: " + isValid);
if (isValid) {
if ($("#dobError").has("span").length > 0) {
$("#dobError").find("span").remove();
}
}
});
I have noticed after adding the logs that the function "customdate is not triggered except when I'm entering a valid date. For example, when the date is 2/2/2000, it's only triggered after entering the last zero in 2000. It will never be triggered when entering 2/2/2033. What am I missing?
Also, is there a better way of using $("MyForm").valid()? as this will trigger validation for all the fields in the form.