A recent requirement I came across was the need to verify that a date being entered into a SharePoint form field was not before today’s date, and if it was then throw back an error message.

Oh what to do?

You could do this via conditional formatting on the field itself, however this then means the field cannot be left blank when a form is submitted, which is fine for most cases but not in my case where the field is only shown after a certain stage is reached.

So how can I allow the form to still be submitted with a blank value if it the stage where the date field exists hasn’t been reached yet, but at the same time check the date is after today’s date when the stage with the date field has been reached?

JavaScript of course!

Use the code below replacing the IDofField text below to match the id of the field within the form (this will usually look something like “Date_x0020_of_x0020_work_x0020_t_6dec11ff-e46f-4e60-9cb3-be76df816cfb_$DateTimeFieldDate”

[javascript]

    dateWorkItem = document.getElementById("Date_x0020_of_x0020_work_x0020_t_6dec11ff-e46f-4e60-9cb3-be76df816cfb_$DateTimeFieldDate");
    dateWork = stringToDate(dateWorkItem.value + "/00/00/00", "dd/MM/yyyy/HH/mm/SS", "/");
    $(dateWorkItem).change(function () {
        dateWork = stringToDate(dateWorkItem.value + "/00/00/00", "dd/MM/yyyy/HH/mm/SS", "/");
        if (dateWork > Date.now()) {
            alert("Date cannot be prior to today - please consult Governance if this is the case")
        }
    });

[/javascript]

This code will add an onChange event handler that will run the check function above every time the date field value changes