Useful scripts I've used

Marcel H_
Tera Guru

Hi Everyone,

I come to the ServiceNow Community a lot for questions that I have, and more often than not I find answers to my questions, or solutions that I can modify to meet my needs. Sometimes though it can be daunting to find specific information, and when it comes to scripting there are so many ways for someone to write and accomplish similar results it can be very confusing for those of us that haven't always done scripting in our careers. So with that I just wanted to share a few scripts that I found very useful to me in my company's production instance. I can't take all the credit for these either, many started out as suggestions from other community members that were modified, so just trying to give back as well.

Truncate comments on notifications:

Mail script used to truncate all the additional information in a journal comment, so that only what was typed into the field originally is added to the notification. Create a new mail script with the following code:

var jString = current.comments.getJournalEntry(1);  

var nString = setJournalString(jString);

template.print(nString);  

 

function setJournalString(jString) {

      var regex = /\d+\W\d+\W\d+\s(.+)\n/;    

      var result = jString.replace(regex, '');  

      return result;  

}

Format a Service Catalog Variable Field as Currency:

Catalog Client Script to enforce a variable field to insert commas at the correct 3 digit intervals and add a dollar sign to the beginning of the number. Also allows for - to designate negative dollar amounts.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {  
 
  if (isLoading || newValue === '') {  
  return;  
  }  
  var result = formatNumber(newValue);  
  if(result == false){  
        alert('Only dollar amounts allowed');  
        return;  
 
  }  
    // To avoid recusrion  
  if(result != newValue){  
      // Change catalog variable field_name to the field on which this onChange script is applied  
      g_form.setValue('u_variance_amount', "$" + formatNumber(newValue));  
 
  }  
}  
function formatNumber(x) {  
  // Regular expression allowing only numeric values
  var reg = /^[\d,$.-]+$/;  
  if(!x.match(reg))  
      return false;  
  else  
      return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");   // Insert commas at correct position  
  }

Validate and Enforce Email Address in Service Catalog Variable Field:

Create and onChange Catalog Client Script with the following javascript:

function onChange(control, oldValue, newValue, isLoading) {  
  if (isLoading || newValue == '') {  
          return;  
    }  
 
  //Email Validation Using OOB Error Checking
    if(oldValue != newValue){      
          g_form.hideFieldMsg('RECORD PRODUCER VARIABLE NAME', true);      

var problemMsg = isEmailValidWithReason(newValue);  

  if (problemMsg != "") {  
        g_form.setValue('RECORD PRODUCER VARIABLE NAME', '');
        alert(newValue + " is an invalid email, " + problemMsg + ".");      
        }      

    }

}

Enforce Phone Number Format in Service Catalog Variable Field:

Create an onChange Catalog Client Script with the following:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue == '') {
        return;
    }
var tempValue = newValue;

//Use Regular Expressions to verify number

var phoneRegex1 = /^\d{3}-\d{3}-\d{4}$/;
var phoneRegex2 = /^(1{3}-1{3}-1{4}|2{3}-2{3}-2{4}|3{3}-3{3}-3{4}|4{3}-4{3}-4{4}|5{3}-5{3}-5{4}|6{3}-6{3}-6{4}|7{3}-7{3}-7{4}|8{3}-8{3}-8{4}|9{3}-9{3}-9{4}|0{3}-0{3}-0{4})$/;
  if(tempValue.match(phoneRegex1) && !tempValue.match(phoneRegex2))

{
return;
}

else {
g_form.setValue('RECORD PRODUCER VARIABLE NAME', '');
alert('Phone number must be in format XXX-XXX-XXXX.');

}

}

Add User from another field to the Watch List:

//Create an array object by splitting the IDs in the watch list comma seperated string into array elements
//Get the sys_id of the user selected in the Approver field
//Create a new object to use the ArrayUtil function

var arr = current.watch_list.split(',');  
var contact = current.u_approver;  
var arrayUtil = new ArrayUtil();

//Use the ArrayUtil object to check if the sys_id of the contact is among the sys_ids in the watch list
//If it is not in the watch list we add the sys_id to the array

if (!arrayUtil.contains(arr, contact)) {  
arr.push(contact);  
}

//Update the watch list field with the sys_ids now in the array. The join() funtion converts the array to a comma seperated string again

current.watch_list = arr.join();

Script for excluding weekends from a Scheduled Job:

This is a script that can be used to prevent Scheduled Jobs for various tasks from running on weekends when a conditional check is used:

function checkWeekdays() {

                      var now = new Date();

                      var day = now.getDay();

                      var result = false;

                      if(day != 0 && day != 6) {

                                              result = true;

                      }

                      return result;

}

checkWeekdays();

Script for getting a user's specific groups:

To call a person's specific groups of which they are a member, and excluding any Parent Groups that they are not a member of, but may be inheriting permissions from, use the following script in a Script Include:

function getMySpecificGroups(){  
  var gr = new GlideRecord('sys_user_grmember');  
  gr.addQuery("user", gs.getUserID());  
  gr.addQuery("group.active", true);  
  gr.query();  
  var array = [];  
  while (gr.next()) {  
          array.push(gr.getValue('group'));  
  }  
  return array;  
}  

Then when building conditions to display items, use the following logic:

Assignment Group - is - javascript:getMySpecificGroups()

2 REPLIES 2

SanjivMeher
Kilo Patron
Kilo Patron

Thanks Marcel. It is helpful.



Please mark this response as correct or helpful if it assisted you with your question.

The SN Nerd
Giga Sage
Giga Sage

Hi Marcel,



May I suggest a modification to "Script for excluding weekends from a Scheduled Job".



The Date() API uses PST.


If you are not on that timezone, the script will not work.



Substitue Date() with GlideDateTime() and use getDayOfWeekLocal().


See correction below.



(function isWeekday() {


var now = new GlideDateTime();


var day = now.getDayOfWeekLocalTime();


return (day != 0 && day != 6);


})()



Regards,


Paul



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022