Date Validation - Client Side
I created a Date variable in a Catalog Item which represented the Date Required. I wanted to check that this data was at least 2 days in the future and NOT on a weekend.
Investigation (Googling)
Initially, I searched the communities for examples of how to Validate dates on the client side.
Many articles suggested that I use of AJAX to check the date on the server side. Suffering any latency for such a trivial task as setting dates seamed to be a bit silly. I finally came across a few examples of client side checking. Below is another example, for sharing:
Sample UI Client Script
Below is a sample UI Client Script which runs entirely on the client and validates a Variable of type Date in a Catalog Item. This script checks to see if the 'date_required' (i.e. NewValue) is >= 2 days in the future and not on a weekend.
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
//get the new and current date/time as an object
var dateObjectNow = new Date();
var dateObjectNew = new Date(newValue);
//get the dates in days - also use floor to convert valeus to integers
var dateNow = Math.floor(dateObjectNow.valueOf()/(1000*60*60*24));
var dateNew = Math.floor(dateObjectNew.valueOf()/(1000*60*60*24));
// Get day of week (Sunday = 0)
var dayOfWeek = dateObjectNew.getDay();
// Check Date if date is 2 or more days in the future and not on the weekend.
var msg;
if (dateNew >= (dateNow + 2) && dayOfWeek > 0 && dayOfWeek < 6) {
msg = 'Date is OK';
g_form.hideFieldMsg('date_required',true);
g_form.showFieldMsg('date_required',msg,'info',false);
}
else {
msg = 'ERROR: Date must be 2 or more days in the future and not on the weekend.';
g_form.hideFieldMsg('date_required',true);
g_form.showFieldMsg('date_required',msg,'error',false);
}
}
https://www.servicenow.com/community/developer-articles/date-validation-client-side/ta-p/2326784