OnSubmit Client Script Examples: Practical Use Cases & Code Snippets

Unlocking Form Efficiency: Practical OnSubmit Client Script Examples in ServiceNow

Posted on [Date] by [Your Name/Alias]

Ever wished you could add a layer of intelligence to your ServiceNow forms, ensuring data integrity and guiding users before they hit that final ‘Submit’ button? That’s where OnSubmit client scripts shine. They’re the unsung heroes of user experience and data validation, giving you the power to intercept form submissions and perform crucial checks or actions. This article dives deep into practical, real-world examples of OnSubmit client scripts, demystifying their usage and showing you how to leverage them for maximum impact.

What Exactly is an OnSubmit Client Script?

Before we jump into the exciting stuff, let’s get a clear understanding of what we’re dealing with. In ServiceNow, client scripts run on the user’s browser. They are triggered by various events on a form, and the onSubmit event is particularly powerful. It fires just before the record is saved to the database. This gives you a unique opportunity to:

  • Validate Data: Ensure all required fields are populated correctly, or that values meet specific criteria.
  • Automate Actions: Pre-populate fields based on other selections, or set default values.
  • Prevent Submissions: Stop users from saving a record if critical conditions aren’t met, preventing bad data from entering your system.
  • Provide User Feedback: Inform users about potential issues or suggest improvements before they commit.

Think of it as a final quality check and smart assistant built right into your forms. It’s a fundamental concept for anyone looking to enhance ServiceNow’s out-of-the-box functionality and streamline business processes. While UI Policies and Data Policies are excellent for declarative configurations, client scripts offer the flexibility and power of JavaScript for more complex scenarios.

The Power of `g_form.getValue()` and `g_form.addErrorMessage()`

At the heart of most OnSubmit client scripts lie two essential methods of the g_form object:

g_form.getValue(fieldName)

This method is your go-to for retrieving the current value of a field on the form. You pass the field’s internal name as an argument, and it returns the value as a string. It’s crucial to remember that even for choice lists or reference fields, getValue() often returns the internal value (like sys_id for references or the option value for choices).

g_form.addErrorMessage(message)

This is your primary tool for user feedback when something isn’t right. When you call this method, a red error message will appear at the top of the form, and critically, it will prevent the form from submitting. This is the magic that stops invalid data in its tracks.

Understanding these two methods is the gateway to writing effective OnSubmit client scripts. Let’s see them in action with some practical examples.

Practical OnSubmit Client Script Examples

Here, we’ll explore common scenarios and provide ready-to-use script examples. Remember to always test your scripts thoroughly in a development or test instance before deploying them to production.

Example 1: Ensuring Critical Fields are Populated (Beyond Basic Required)**

ServiceNow has built-in “Required” field attributes. However, sometimes you need to enforce a combination of fields or have a more nuanced validation. For instance, on an Incident form, if the “Assignment group” is set to “Service Desk,” you might want to ensure the “Assigned to” field is also populated. This prevents tickets from lingering in an unassigned state within a specific group.


function onSubmit() {
    // Get the values of the Assignment Group and Assigned To fields
    var assignmentGroup = g_form.getValue('assignment_group');
    var assignedTo = g_form.getValue('assigned_to');

    // Check if the Assignment Group is 'Service Desk' (replace with actual sys_id or display value if needed)
    // For display value: g_form.getDisplayBox('assignment_group').value
    // For sys_id (more robust): g_form.getReference('assignment_group', function(group) { ... }); - This is a more advanced async call.
    // For simplicity in this example, we'll assume we know the display value.
    if (g_form.getDisplayBox('assignment_group').value === 'Service Desk') {
        // If Assignment Group is 'Service Desk', check if Assigned To is empty
        if (g_form.getValue('assigned_to') == '') {
            // Add an error message and prevent submission
            g_form.addErrorMessage('For the Service Desk assignment group, the "Assigned to" field must be populated.');
            return false; // This is crucial - it stops the submission
        }
    }

    // If all checks pass, return true to allow submission
    return true;
}
        

Explanation:

This script first retrieves the display value of the “Assignment Group” field. If it matches “Service Desk,” it then checks if the “Assigned to” field is empty using g_form.getValue('assigned_to'). If both conditions are true, an error message is displayed using g_form.addErrorMessage(), and return false; halts the submission process. If the conditions aren’t met, or if the assignment group isn’t “Service Desk,” the script proceeds, and return true; allows the record to be saved.

Real-World Scenario:

This is highly relevant for IT support teams. By enforcing assignment, you reduce the chances of incidents being missed or sitting unassigned in a busy queue. It ensures accountability from the moment a ticket is created or modified.

Example 2: Preventing Submission if a Critical Reference Field is Not Selected**

Imagine a Change Request form where a “Risk Assessment” must be completed before the change can be implemented. If the “Risk Assessment” field (a reference to another table) is empty, you shouldn’t allow the change to be submitted.


function onSubmit() {
    // Check if the 'Risk Assessment' field (assuming its internal name is 'risk_assessment') is empty.
    if (g_form.getValue('risk_assessment') == '') {
        // If it's empty, display an error message.
        g_form.addErrorMessage('A Risk Assessment must be linked before submitting this Change Request.');
        // Prevent the submission.
        return false;
    }

    // If the field has a value, allow the submission.
    return true;
}
        

Explanation:

This is a straightforward validation. It checks if the reference field risk_assessment has a value. If it’s empty (''), an error message is displayed, and the submission is blocked.

Real-World Scenario:

Essential for compliance and risk management. In regulated industries, ensuring proper documentation and risk analysis is paramount before proceeding with significant changes to systems. This script enforces that critical step.

Example 3: Conditional Field Validation Based on Selection**

On a Customer Service Request form, if the user selects “Software Installation” as the “Request Type,” you might require them to specify the “Software Name.” If they choose another type, the “Software Name” field might be optional.


function onSubmit() {
    // Get the value of the 'Request Type' field
    var requestType = g_form.getValue('request_type');

    // Check if the request type is 'Software Installation'
    if (requestType === 'software_installation') { // Assuming 'software_installation' is the value for this choice
        // Now, check if the 'Software Name' field is empty
        if (g_form.getValue('software_name') == '') {
            g_form.addErrorMessage('For "Software Installation" requests, please specify the "Software Name".');
            return false; // Prevent submission
        }
    }

    // If the request type is not 'Software Installation' or if Software Name is filled, allow submission.
    return true;
}
        

Explanation:

This script uses a conditional check. It first determines the selected value for request_type. Only if that value is 'software_installation' does it proceed to check if the software_name field is empty. If it is, an error is thrown, and submission is prevented. Otherwise, the script allows the submission.

Real-World Scenario:

Improves data quality for specific service requests. Ensures that when a particular service is requested, all necessary details related to that service are captured, leading to faster and more accurate fulfillment.

Example 4: Ensuring a Date is in the Future**

For scheduling events or planned outages, you might want to ensure that the “Planned Start Date” is always in the future. Submitting a record with a past date for a future event doesn’t make sense.


function onSubmit() {
    // Get the value of the 'Planned Start Date' field
    var plannedStartDate = g_form.getValue('planned_start_date');

    // Check if the plannedStartDate field is not empty
    if (plannedStartDate != '') {
        // Convert the date string to a JavaScript Date object
        // ServiceNow stores dates in YYYY-MM-DD HH:MM:SS format
        // We need to adjust for potential time zone differences and local formats.
        // A safer approach is to use ServiceNow's built-in GlideDateTime for comparisons,
        // but for a simple "future date" check, string comparison after parsing can work if consistent.
        // Let's use a more robust approach with GlideDateTime.

        var plannedGlideDateTime = new GlideDateTime(plannedStartDate);
        var nowGlideDateTime = new GlideDateTime(); // Gets current date and time

        // Compare the two dates. If planned date is before or equal to 'now', show error.
        if (plannedGlideDateTime.before(nowGlideDateTime) || plannedGlideDateTime.equals(nowGlideDateTime)) {
            g_form.addErrorMessage('The "Planned Start Date" must be in the future.');
            return false;
        }
    }

    // If date is in the future or field is empty (if empty is allowed), allow submission.
    return true;
}
        

Explanation:

This script leverages ServiceNow’s GlideDateTime API, which is the most reliable way to handle date and time comparisons. It gets the value of the planned_start_date, converts it to a GlideDateTime object, and compares it against the current date and time (also obtained using GlideDateTime). If the planned date is not strictly in the future, an error is shown, and submission is prevented.

Real-World Scenario:

Crucial for Change Management and Release Management. Ensures that scheduled activities are accurately planned, avoiding confusion and potential conflicts with past dates.

Example 5: Validating Email Format (for a Custom Field)**

While ServiceNow has some built-in email validation for standard email fields, you might have a custom field where you need to ensure a valid email format is entered.


function onSubmit() {
    // Get the value of the custom email field (assuming internal name is 'custom_email')
    var emailValue = g_form.getValue('custom_email');

    // Regular expression for basic email validation
    // This regex is not exhaustive but covers most common cases.
    var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

    // Check if the email field is not empty and if it doesn't match the regex
    if (emailValue != '' && !emailRegex.test(emailValue)) {
        g_form.addErrorMessage('Please enter a valid email address in the "Custom Email" field.');
        return false;
    }

    // Allow submission if the email is valid or the field is empty
    return true;
}
        

Explanation:

This script uses a regular expression (regex) to check the format of the email address entered into the custom_email field. The emailRegex.test(emailValue) method returns true if the value matches the pattern, and false otherwise. If the field is not empty and the format is invalid, an error message is displayed, and submission is blocked.

Real-World Scenario:

Ensures consistent and usable email addresses are captured for customer communication, marketing campaigns, or user notifications, reducing bounce rates and improving outreach effectiveness.

Troubleshooting Common Issues with OnSubmit Client Scripts

Even the best scripts can sometimes behave unexpectedly. Here are some common pitfalls and how to address them:

1. Script Not Firing

Possible Causes:

  • Incorrect Table/Form View: Ensure the client script is associated with the correct table and specific form view(s) if applicable.
  • UI Policy Conflicts: A UI Policy might be hiding the fields or disabling interactions that prevent the script from running. Check the order of execution for UI Policies and Client Scripts.
  • Caching Issues: Sometimes, browser or ServiceNow instance caching can prevent new scripts from loading. Try clearing your browser cache or performing a hard refresh (Ctrl+F5 or Cmd+Shift+R).
  • Syntax Errors: A single misplaced semicolon or typo can break the entire script. Use the browser’s developer console (F12) to check for JavaScript errors.

Troubleshooting Steps:

  • Verify the script’s conditions (table, type, onLoad, onChange, onSubmit).
  • Temporarily disable other client scripts or UI policies on the same form to isolate the issue.
  • Use g_form.log('Script is running!'); at the beginning of your script to confirm it’s being executed.

2. `g_form.getValue()` Returning Unexpected Values

Possible Causes:

  • Field Type Mismatch: For reference fields, getValue() returns the sys_id. For choice lists, it returns the option’s value, not the label.
  • Asynchronous Operations: If your script relies on data from other tables using asynchronous calls (like g_form.getReference()), you need to handle the response within the callback function.
  • Field Not Yet Loaded: In rare cases, on complex forms, a field might not be fully loaded when the script runs.

Troubleshooting Steps:

  • Use g_form.log('Assignment Group Value: ' + g_form.getValue('assignment_group')); to see exactly what value is being retrieved.
  • For reference fields, if you need the display value, use g_form.getDisplayBox('field_name').value (but be aware this might not always be the most reliable if the display value changes dynamically). A more robust method for complex scenarios is using g_form.getReference().

3. `g_form.addErrorMessage()` Not Preventing Submission

Possible Causes:

  • Missing `return false;` Statement: This is the most common reason. The error message is displayed, but the script doesn’t explicitly tell ServiceNow to stop the submission.
  • Script Error After `addErrorMessage()`: If there’s a subsequent syntax error or uncaught exception in your script after the error message is added, it might interrupt the normal flow and potentially allow submission.

Troubleshooting Steps:

  • Ensure that every condition where you call g_form.addErrorMessage() is followed immediately by return false;.
  • Structure your script so that the validation logic is contained within conditional blocks that lead to either return false; or return true;.

4. Performance Issues on Large Forms

Possible Causes:

  • Complex Logic or Loops: Very complex calculations or inefficient loops within the client script can slow down form submission.
  • Excessive DOM Manipulation: While less common with onSubmit scripts, aggressive manipulation of the DOM can impact performance.
  • Asynchronous Calls: If you’re making multiple asynchronous GlideAjax calls within the onSubmit script, the total execution time can increase.

Troubleshooting Steps:

  • Optimize your JavaScript code.
  • If possible, move complex server-side logic to Business Rules or Script Includes that can be called via GlideAjax (though for validation, client-side is usually preferred).
  • Minimize the number of field value retrievals.
  • Use browser developer tools to profile script execution time.

Interview Relevance: Mastering OnSubmit Client Scripts

When you’re in a ServiceNow technical interview, demonstrating a solid understanding of client scripts, especially onSubmit scripts, can set you apart. Interviewers often look for:

1. Core Concepts:

Be ready to explain:

  • What client scripts are and where they run.
  • The purpose and execution order of onLoad, onChange, and onSubmit scripts.
  • The role of the g_form object and its key methods (getValue, setValue, addErrorMessage, getReference, getDisplayBox, hideFieldMsg, etc.).
  • The importance of return false; for preventing submissions.

2. Practical Problem-Solving:

You’ll likely be given scenarios and asked how you’d implement a solution using client scripts. For example:

  • “How would you ensure that a ‘Due Date’ is always set to be at least 3 days after the ‘Start Date’?”
  • “Describe how you would prevent a user from submitting a request if they haven’t selected a valid configuration item for a Change Request.”
  • “Explain the difference between using g_form.getValue('reference_field') and g_form.getReference('reference_field', callback).”

Be prepared to write code snippets or pseudocode on the fly.

3. Best Practices and Pitfalls:

Show that you understand not just how to write scripts, but how to write *good* scripts:

  • Mention the importance of clear naming conventions for fields and scripts.
  • Discuss error handling and user feedback.
  • Talk about performance considerations, especially for complex forms.
  • Explain when to use a UI Policy versus a Client Script. (UI Policies are generally preferred for simple field visibility, mandatory, or read-only changes due to better performance and declarative nature. Client Scripts are for complex logic, dynamic behavior, or validations that UI Policies can’t handle.)

4. Understanding Asynchronous Operations:

For more advanced roles, understanding g_form.getReference() and GlideAjax (GlideRecord on the server side) will be crucial. Being able to explain how to handle data fetched asynchronously is a key differentiator.

By mastering these onSubmit client script examples and understanding the underlying principles, you’ll be well-equipped to tackle complex form validations and enhance user experiences in ServiceNow, making you a valuable asset in any technical interview.

Conclusion

OnSubmit client scripts are indispensable tools for any ServiceNow administrator or developer. They empower you to enforce data integrity, guide user actions, and significantly improve the overall usability of your forms. By understanding the core concepts and practicing with real-world examples like the ones discussed, you can unlock the full potential of your ServiceNow platform, ensuring cleaner data, more efficient processes, and happier users.

Start experimenting, build robust validations, and watch your ServiceNow forms transform from simple data entry tools into intelligent interfaces that actively support your business workflows.

Keywords: ServiceNow, OnSubmit Client Script, Client Scripts, Form Validation, JavaScript, g_form, ServiceNow Development, ServiceNow Best Practices, ServiceNow Administration, Data Integrity, User Experience, Troubleshooting.

Disclaimer: Always test client scripts in a non-production environment before deploying to production.

Scroll to Top