Streamlined Form Validation and Calculation with Common Scripts in ServiceNow
Often, you might need to perform validations on form fields and calculate values based on multiple fields. While there are built-in validators for catalog variables, custom validation and calculation for form fields are still not available.
This guide shows how to create a common script for validation and calculation in ServiceNow.
Use Case 1:
Objective: Validate that a string field (e.g., Candidate ID) meets specific criteria, such as being a 5-character alphanumeric string.
To do this, I created a table with below fields.
Script 1
Name: Common Evaluation Script
Type: OnLoad
Purpose: Define all validation functions for the form, making them available for use by other scripts.
function onLoad() {
// Add any code you need on load
}
// create validation functions that can be accessed by any other client script for this table
/*** Validates the ID if it is an alphanumeric, return the message to be displayed ***/
function validateID(param) {
var pattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{5}$/; //matches alphabets, numbers and maximum 5 characters
var obj = {};
obj = param.match(pattern) ? {
match: true
} : {
match: false,
msg: "The candidate ID should be 5 chars alphanumeric"
};
return JSON.stringify(obj);
};
Script 2:
Name: Validate Candidate ID
Type: onChange
Field: Candidate ID
Purpose: Calls the validateID
function to check if the entered value is valid.
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var response = JSON.parse(validateID(newValue));
(!response.match) ?
(g_form.setValue('u_user_id', ''),
g_form.showFieldMsg('u_user_id', response.msg, "error")) : null;
}
Use Case 2: Calculating Accumulative Scores
Objective: Calculate the total score based on multiple fields (e.g., Technical Acumen, Expertise) and update the Total Score field.
Add below code in the Common Shared Evaluation onLoad script so it looks like below:
function onLoad() {
// Blank since we're just creating a shared function for this table
}
// Shared function that can be accessed by any other client script for this table
/*** Validates the ID if it is an alphanumeric, return the message to be displayed ***/
function validateID(param) {
var pattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{5}$/; //matches alphabets, numbers and maximum 5 characters
var obj = {};
obj = param.match(pattern) ? {
match: true
} : {
match: false,
msg: "The candidate ID should be 5 chars alphanumeric"
};
return JSON.stringify(obj);
}
/*** Calculates the scores passed and return the total ***/
function calculateScore(fieldsArr) {
var sum = fieldsArr.map(function(num) {
// Remove commas and convert to integer
var cleanedNum = num.replace(/,/g, ''); // Remove commas
return parseInt(cleanedNum, 10);
}).filter(function(num) {
// Keep only valid numbers
return !isNaN(num);
}).reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
return sum;
};
Create 2 more client scripts for onchange of each field:
Name: Update Total Score
Type: onChange
Field: Technical Acumen and Expertise
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var fieldsArray = [];
fieldsArray.push(newValue, g_form.getValue("u_technical_acumen"));
var score = calculateScore(fieldsArray);
g_form.setValue("u_total_score",score);
}
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var fieldsArray = [];
fieldsArray.push(newValue, g_form.getValue("u_expertise"));
var score = calculateScore(fieldsArray);
g_form.setValue("u_total_score", score);
}
Summary
By organizing validation and calculation scripts into reusable functions, you ensure consistency and ease of maintenance across forms. Use these scripts to enforce field constraints and perform accumulative calculations effectively.
Additional Notes
- This approach does not replace the use of
GlideAjax
andg_scratchpad
. It is an alternative method for implementing client-side validations and calculations. - UI Scripts: UI Scripts are another option for creating reusable client-side code. These scripts are intended to be global and can be referenced in client scripts, but it’s essential to ensure they are correctly set up and accessible.
- Using a common OnLoad script for validations and calculations is beneficial when multiple onChange scripts utilize the same logic or function. By centralizing the logic in a common script, you can easily update and maintain the validation and calculation processes, ensuring consistency across all related client scripts.
References
Solved: Attach a common onchange function to multiple fiel… — ServiceNow Community