Client-side Date Validation in ServiceNow

getting the validation right

In the years I’ve been working with ServiceNow the accepted way to do date validation on the client side was to use an AJAX script include that called the GlideSystem date/time functions.  This worked but it seemed to be to be an overly complicated way to do something very basic.   I set out to find a way to simplify client-side date validation and I turned to native JavaScript to do it.

I began with the Date class.  The Date class has a few different constructor variations; we are only interested in two.

The first constructor has no input: Date();  That gives the current date/time.

The second constructor takes a date string: Date("2017-12-01");  The creates a date object and parses the string to create a date.  Dates are represented in the Date class as the number of milliseconds from January 1, 1970.  To access that number the class provides the method valueOf().

To an example, a common use case is to not allow a date to be in the past.  In our example, we are going to use a custom field that represents when a task that’s on hold will be moved back to work in progress.  We obviously don’t want an on hold expiration to be in the past.  To validate this, we will create an on change client script.  In the body of the script we do this:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {

if (isLoading || newValue === '') {
return;
}
//get the entered date string
var dtstring = g_form.getValue('u_on_hold_expriation');
//convert the string to a JavaScript Date/Time
var dt = new Date(dtstring);
//get the current date/time
var rightNow = new Date().valueOf();
//convert entered date to milliseconds
var dateToCheck = new Date(dtstring).valueOf();
//Compare the two numbers
if (dateToCheck < rightNow) {
alert('You cannot select a date in the past.');
g_form.setValue('u_on_hold_expriation','');
}
}
This same concept can be applied to comparing two dates on a form.  For example, if you had a start date and an end date you would want to check the end date to ensure it wasn’t before the start date.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

if (isLoading || newValue === '') {
return;
}


//get the entered date string

var startDate = g_form.getValue('work_start');
var endDate = g_form.getValue('work_end');
//convert the string to a JavaScript Date/Time
var startDateValue = new Date(startDate).valueOf();
var endDateValue = new Date(endDate).valueOf();
//Compare the two numbers
if (startDateValue > endDateValue) {
alert('End date must be after start date.');
g_form.setValue('work_end','');
}
}
This method is simple and clear.  By using the native Date class in JavaScript, we can avoid making complex AJAX calls.[/av_textblock]

2018-06-19T20:00:31+00:00