john_roberts
Mega Guru

I just came across a case where someone was comparing two date fields on the client to validate that the one was later than the other. To accomplish this they created a script include to compare dates on the server, then a client script was used to make an AJAX call to run the check in the script include.
The same check can be performed completely on the client saving the time it takes for a server round trip. Helper methods can be found in the calendar.js file on your client.

Here's a couple common uses:



/*
* onChange Client Script - change_request
* should be set to run on change of start_date and end_date
* Alert if planned end date is before planned start date
*/
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue == '') {
return;
}

var end = g_form.getValue("end_date");
var start = g_form.getValue("start_date");
// skip if start or end is blank
if (start == "" || end == "") {
return
}

// get user's date time display format
var format = g_user_date_time_format;
var isEndBeforeStart = compareDates(start, format, end, format);

// 1 (true) if start is greater than end
// 0 if end is greater than start of if they are the same
// -1 if either of the dates is in an invalid format

if (isEndBeforeStart) {
alert("End must be after start");
}
}


Caution with this next one since it may cause issues for users using a computer set to a different timezone than the user's ServiceNow account is using. The Date() object assumes the timezone of the browser.


/*
* onChange Client Script - change_request start_date field
* Alert if planned start date is before right now
*/
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue == '') {
return;
}

//get start date
var start = newValue;
//get Date object using user's display format
var dt = getDateFromFormat(start, g_user_date_time_format);
var rightNow = new Date();
if (dt < rightNow) {
alert("Start time is in the past, changing type to emergency.");
g_form.setValue("type", "Emergency");
}
}

12 Comments