Time fields validation

scottangehr
Giga Guru

Hello friends

Happy Knowledge week!  How all is well.

I have an ask that I'm having a slight issue trying to make happen.

I have a Record Producer with variables that I need to make sure each variable is after the next.

These fields are string fields with the validation regex as Time (00:00) 24 hr.

I need there to be a validation and error that the field entered is after the previous field.

scottangehr_0-1715017301499.png

Meal Out should be after Time In
Meal In should be after Time In & Meal Out
Time Out should be after Time In, Meal Out, & Meal In

 

I originally created these fields as Date/Time but the business only wanted times

7 REPLIES 7

Try going through this post to see if you are able to convert two string fields to time.

Solved: Convert String to GlideDateTime - ServiceNow Community

If you need another set of eyes, let me know. These are fun challenges

Played around a little more w/ a background script.

Let's say the In Time is entered in as 08:30 (you'll need to make sure the entered value is formatted correctly).

When you send the value to a script include for processing, the script include could parse the data like so:

 

var inTime = "08:30"
var gd = new GlideDate();
gs.info(gd.getValue());
var gdt = new GlideDateTime(gd+" "+inTime);
gs.info(gdt);

 

The above output will be this:

*** Script: 2024-05-08
*** Script: 2024-05-08 08:30:00

Now, if you have two times (IN and OUT), you can compare like so:

 

var inTime = "08:30"
var outTime = "10:30"
var gd = new GlideDate();
gs.info(gd.getValue());
var gdtIN = new GlideDateTime(gd+" "+inTime);
var gdtOUT = new GlideDateTime(gd+" "+outTime);
gs.info(gdtIN);
gs.info(gdtOUT);

gs.info(gdtIN.compareTo(gdtOUT)); //this will be either 1 or -1, see API info

 

The compareTo API info is here: 

GlideDateTime | ServiceNow Developers

 

Hope this helps

Good day magee. I think I forgot to mention that I'm using a Catalog Client Script.  Here is my script and what I'm trying to solve for.

The user enters in time format 12:34 (12hr format).
If the time out is prior to any of the preceding fields, it should show an error.

scottangehr_0-1717076405195.png

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    var startTime = g_form.getValue('u_fri_meal_in');
    var endTime = g_form.getValue('u_fri_time_out');

    if (startTime == '' || endTime == '')
        return;

    // check if conflicting start time
    if (startTime >= endTime()) {
	    g_form.setValue('u_fri_time_out', null);
        g_form.hideFieldMsg('u_fri_meal_in');
        g_form.showFieldMsg('u_fri_time_out', new GetMessage().getMessage('Time Out must be after Meal In'), 'error');
	
    } else {
        g_form.hideFieldMsg('u_fri_time_out');
        g_form.hideFieldMsg('u_fri_meal_in');
    }
}

 

Thanks again for your help!
Scott