Skip to Content

Conditional Mandatory Fields

Make fields mandatory based on the value of another field (e.g., require close notes only when state is Resolved).

onChange Table: incident Field: state
#mandatory-fields #conditional #validation #onChange

Script Code

JavaScript
1function onChange(control, oldValue, newValue, isLoading, isTemplate) {
2  // Exit if form is loading
3  if (isLoading) {
4    return;
5  }
6
7  // Configuration: Define your conditions
8  // Change these values to match your requirements
9  var resolvedState = '6';        // The state value that triggers mandatory fields
10  var mandatoryFields = [         // Fields to make mandatory
11    'close_code',
12    'close_notes'
13  ];
14
15  // Check if the new state matches the resolved state
16  if (newValue === resolvedState) {
17    // Make fields mandatory
18    mandatoryFields.forEach(function(fieldName) {
19      g_form.setMandatory(fieldName, true);
20    });
21
22    // Optional: Show info message to user
23    g_form.addInfoMessage('Close code and close notes are required for resolved incidents.');
24
25  } else {
26    // Remove mandatory when state changes back
27    mandatoryFields.forEach(function(fieldName) {
28      g_form.setMandatory(fieldName, false);
29    });
30  }
31}

How to Use

1. Create an onChange Client Script on your table 2. Set the field to the one that controls the mandatory logic 3. Update `resolvedState` and `mandatoryFields` for your use case 4. Optionally add an onLoad script to handle when form first opens

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts