While you can perform certain actions via business rules in ServiceNow, using a business rule for this specific case isn't the ideal approach. Business rules are typically server-side scripts and are primarily used for operations such as data manipulation, validation, or business logic execution on the server side, rather than providing immediate feedback to the user.
Reasons Business Rules Aren’t Ideal for This Case:
- Immediate Feedback: Business rules don't provide immediate feedback on the form itself because they run on the server after the data is submitted or on specific triggers.
- Field Message Display: Business rules don't directly interact with the user interface to display messages or clear fields in real-time on the form.
However, if you want to enforce validation on the server side, perhaps as an additional measure, you could use a business rule. Here’s how you could implement it:
Steps to Create a Business Rule:
-
Navigate to Business Rules:
- Go to the ServiceNow navigator, type "Business Rules," and select the appropriate option under System Definition.
- Click "New" to create a new business rule.
-
Configure the Business Rule:
- Name: Provide a descriptive name, like "Validate Hostname Prefix on Save".
- Table: Set this to
sc_task.
- When to Run: Select "before" and the "Update" event, so it validates before the record is updated.
- Conditions: You might leave this empty if you want the validation to run every time.
-
Script Logic:
Here is a sample script for the business rule:
(function executeRule(current, previous /*null when async*/) {
// List of valid prefixes
var validPrefixes = ['dc', 'fs', 'aws'];
// Function to check if the hostname has a valid prefix
function isValidHostnamePrefix(hostname) {
for (var i = 0; i < validPrefixes.length; i++) {
if (hostname.startsWith(validPrefixes[i])) {
return true;
}
}
return false;
}
// Validate the hostname before saving
if (current.hostname && !isValidHostnamePrefix(current.hostname)) {
current.hostname = ''; // Clear the hostname
gs.addErrorMessage('Hostname must start with dc, fs, or aws');
// Prevent the record from saving with an incorrect hostname
current.setAbortAction(true);
}
})(current, previous);
-
Save the Business Rule:
- Save your setup by clicking the "Submit" or "Update" button.
Key Considerations:
- Delayed Feedback: Since the business rule runs on the server, users will see feedback only after trying to save the form, which might not be as user-friendly as client-side validation.
- Data Integrity: It ensures that no incorrect data is saved to the database, acting as a safeguard even if client-side validation is bypassed.
Overall, while it's good practice to have server-side validation for critical operations, for real-time user feedback and field interaction, client scripts are preferred in ServiceNow. You can use both approaches in tandem to ensure both a good user experience and data integrity.