Skip to content

Commit 1657612

Browse files
Field Validation based on Form View in Server Side (#2566)
* Create README.md * Create fieldValidationinBR.js * README.md
1 parent c576458 commit 1657612

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
ServiceNow business rule for server-side field validation based on form views.
2+
3+
This ServiceNow business rule provides comprehensive server-side validation for multiple form fields when users access specific form views. The script ensures data integrity by validating that critical fields contain expected values before allowing record submission, making it perfect for enforcing business rules and data consistency across your ServiceNow instance.
4+
5+
What This Script Does:
6+
7+
The business rule automatically validates multiple fields against predefined expected values when a specific form view is accessed. Key features include:
8+
9+
View-Based Validation: Only triggers when accessing a specified form view
10+
Multiple Field Support: Validates multiple fields simultaneously with customizable criteria
11+
Required Field Checking: Ensures mandatory fields are not empty or null
12+
Value Validation: Confirms fields contain expected values according to business rules
13+
User-Friendly Messaging: Provides clear, consolidated error messages explaining all validation failures
14+
Server-Side Security: Performs validation on the server to prevent client-side bypassing
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
(function executeRule(current, previous /*null when async*/ ) {
2+
var TARGET_VIEW_NAME = 'your_target_view_name';
3+
var FIELD_VALIDATIONS = [
4+
{field: 'field1', expectedValue: 'value1', errorMsg: 'Field 1 validation failed'},
5+
{field: 'field2', expectedValue: 'value2', errorMsg: 'Field 2 validation failed'},
6+
{field: 'field3', expectedValue: 'value3', errorMsg: 'Field 3 validation failed'}
7+
];
8+
9+
var gURI = "";
10+
try {
11+
gURI = gs.action.getGlideURI();
12+
} catch(e) {
13+
return;
14+
}
15+
16+
var view_name = gURI.get('sysparm_view');
17+
18+
if (view_name == TARGET_VIEW_NAME) {
19+
var validationErrors = [];
20+
21+
for (var i = 0; i < FIELD_VALIDATIONS.length; i++) {
22+
var validation = FIELD_VALIDATIONS[i];
23+
var fieldValue = current.getValue(validation.field);
24+
25+
if (gs.nil(fieldValue)) {
26+
validationErrors.push(validation.field + ' is required');
27+
continue;
28+
}
29+
30+
if (fieldValue != validation.expectedValue) {
31+
validationErrors.push(validation.errorMsg);
32+
}
33+
}
34+
35+
if (validationErrors.length > 0) {
36+
gs.addErrorMessage(gs.getMessage("Validation failed: {0}", validationErrors.join(', ')));
37+
}
38+
}
39+
})(current, previous);

0 commit comments

Comments
 (0)