Restrict users from selecting past date (Date Validation)

Let’s learn how to restrict user form selecting past date. We can do this through JavaScript.

Below we have a Lead form, where we have a Target Date field. The need is to restrict user from saving the lead form having passed data on Target date field.

Lead Form

Below is the code which can we used:

(function () { }(window.BankNotes = window.BankNotes || {}));
(function (BankNotesFilter) {
/* Function ValidateTargetDate: This would trigger on OnChange event of Target Date field. Which would restrict user from selecting past date under Target Date field.*/
BankNotesFilter.ValidateTargetDate = function (executionContext) {
var formContext = executionContext.getFormContext();
var dateFieldVal = formContext.getAttribute("blog_targetdate").getValue(); // TargetDate Field
var today = new Date();
var todaydate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);

if (dateFieldVal < todaydate) {
formContext.getAttribute("blog_targetdate").setValue(null);
formContext.getControl("blog_targetdate").setNotification("Selected date should be greater or equal to today","101");
}
else {
formContext.getControl("blog_targetdate").clearNotification("101");
// alert("Selected Target date greater than today");
}
};
}(window.BankNotes.BankNotesFilter = window.BankNotes.BankNotesFilter || {}));

The code restrict user from selecting past date on Target Date field.
If, user select past date under Target Date field then the field value will be cleared out showing notification(“Selected date should be greater or equal to today”) on the field.

Just, we need to call the above code on OnChange event of Target Date field:

Call the Function: BankNotes.BankNotesFilter.ValidateTargetDate

The value will be cleared out, on selection of past date

When a user select today’s or any future date, system will allow user to select the date.

User able to select any future/current date.

Hope this helps!