How to Implement a Confirmation Dialog Box using Client Scripts in ServiceNow
- nathanlee142
- Mar 19
- 13 min read
Updated: 4 hours ago

ServiceNow developers often encounter scenarios where users need to confirm an action before the system proceeds. For example, when a user attempts to submit a form that violates a business rule or performs a critical operation (like deleting a record or scheduling an event outside allowable dates), it's prudent to ask “Are you sure?” before finalizing the action. A confirmation dialog box is a simple yet effective way to prompt users for this verification. It improves data accuracy and user experience by giving users a chance to review or cancel an action that might be undesired. In ServiceNow, this can be achieved on the client side using an onSubmit client script that leverages the browser’s native confirmation dialog.
In this article, we’ll explain why a confirmation dialog is needed in a typical use case, discuss the pitfalls of naive implementations, and then provide a detailed, step-by-step solution. You’ll learn how to create a confirmation dialog using a client script, see the code in action, and get tips on best practices, testing, and troubleshooting. By the end, you’ll be able to implement a confirmation prompt that runs when a user submits a form in ServiceNow, preventing invalid submissions unless the user explicitly confirms.
Problem Statement
Let’s consider a common use case: validating date fields on a Change Request form. Suppose we have a Planned Start date and an Actual Start date. Business rules dictate that the Actual Start should never be earlier than the Planned Start. If a user enters an Actual Start date that is before the Planned Start, the system should warn the user and require confirmation to proceed (otherwise, the user might be entering incorrect data). If the user confirms, the submission goes through; if not, the submission should be aborted.
A naive approach might be to use an onChange client script on the date fields to pop up window.confirm(). However, this approach can fail – developers found that even if the user clicked “OK” in the confirm dialog, the form submission did not always proceed as expected. This is because an onChange script only runs when a field value changes, and it doesn’t inherently control the form submission flow. In our example, a user might trigger the confirm on field change but still have the form blocked or in an uncertain state when saving. The proper solution is to use an onSubmit client script, which runs at the moment of form submission and can definitively allow or cancel the save operation.

A typical browser confirmation dialog prompts the user to confirm or cancel an action. In ServiceNow, we can leverage this native dialog using an onSubmit client script.
To clarify the requirements, let’s outline the logic in a flow diagram. The onSubmit script needs to check the date values when the form is submitted and decide whether to interrupt the save:

Flowchart: Logic for confirmation on form submit. If the “Actual Start” is earlier than “Planned Start”, a confirmation dialog is shown. The user’s choice of OK or Cancel determines whether the submission proceeds or is aborted.
In summary, the problem is ensuring that users confirm potentially problematic input (in this case, an Actual Start date before the Planned Start date) at the time of form submission. We need to implement this confirmation in a way that truly stops the submission if the user cancels. The solution will involve an onSubmit client script that uses the confirm() dialog and returns false to abort submission when needed.
Solution
The solution is to create an onSubmit client script on the relevant table (e.g. the Change Request table). This script will perform the check and invoke window.confirm() to prompt the user. By using onSubmit, we can prevent the record from saving to the database unless the user explicitly allows it (by clicking OK). This approach is recommended by ServiceNow for client-side validation at submit time – for example, official ServiceNow documentation notes that an onSubmit script can generate a confirmation dialog for important validations.
Below is a step-by-step guide to implement the confirmation dialog using an onSubmit client script:
Navigate to Client Scripts in ServiceNow: In your instance’s left navigation filter, type “Client Scripts”. Under System Definition, click Client Scripts to open the list of client scripts.
Navigating to System Definition > Client Scripts via the Application Navigator.
Create a New onSubmit Client Script: Click the New button to create a new client script record. In the client script form, fill in the following fields:
Name: A descriptive name, e.g. “Confirm Actual Start Date”.
Table: Select the table the script applies to (for our example, Change Request [change_request]).
Type: Select onSubmit (so the script runs when the form is submitted).
UI Type: Choose All if you want the script to run in both classic and Service Portal interfaces (the default “Desktop” means it would not run in Service Portal).
Active: True (ensure the script is active).
Global: True (unless you want to restrict to a specific view).
Implement the Confirmation Logic in Script: In the Script field of the client script form, write a JavaScript function onSubmit() that performs the following:
Retrieve the Planned Start and Actual Start field values using g_form.getValue('<field_name>'). (Use the correct field names from your form, e.g. start_date for Planned Start, work_start for Actual Start in Change Request).
If either field is empty, allow the form to submit (no confirmation needed in that case).
Parse the date strings into a comparable format. ServiceNow provides the utility getDateFromFormat() for this purpose, along with user-specific format strings g_user_date_time_format (for date/time) or g_user_date_format (for date-only). These ensure the date comparison honors the logged-in user’s date format. Convert both dates to a numeric timestamp (e.g., milliseconds since epoch).
If Actual Start is earlier than Planned Start (i.e., actualStart < plannedStart in terms of timestamp), use confirm() to display a confirmation dialog to the user. The confirm() function will return true if the user clicked OK, or false if the user clicked Cancel.
If the user clicked Cancel (i.e., the confirm returns false), have the onSubmit function return false. In ServiceNow, returning false from an onSubmit client script aborts the form submission, preventing the record from saving. If the user clicked OK, simply allow the function to return true (or fall through), which permits the submission to continue.
Save the Client Script: Click Submit (or Save) on the client script form to save your new script. The confirmation logic is now in effect for users of the specified table.
With these steps completed, whenever a user tries to submit the form, the script will execute and present a confirmation dialog if the condition is met. If the user confirms, the form submits; if not, the submission is canceled (nothing is saved). We’ll now look at the code example in detail.
Code Example
Below is the full code for the onSubmit client script implementing the confirmation dialog logic, with commentary:
Let’s break down what this script does:
It grabs the values of the relevant fields using the g_form API. (The g_form object is provided by ServiceNow to client scripts for interacting with form fields.)
It checks for empty values and skips confirmation in that case (returning true means the submission will not be blocked by this script).
It uses g_user_date_time_format together with getDateFromFormat() to handle date parsing in the user’s locale format. This is important – a date string like “04/25/2025 10:00” vs “2025-04-25 10:00” will be correctly interpreted according to the current user’s preferences. Using these APIs is a best practice for date/time in client scripts.
The if (actualStartMs < plannedStartMs) condition identifies when the Actual Start is earlier than Planned Start. In that case, we build a confirmation message string and call confirm(message). The message clearly explains the situation and what clicking OK or Cancel will do.
If the user clicks Cancel, confirm() returns false, and we add an error message to the form (g_form.addErrorMessage) to let the user know why the submission was stopped. Then we return false from onSubmit – this tells ServiceNow to cancel the submission. The form will not be saved, keeping the record in its pre-submission state for the user to adjust.
If the user clicks OK, confirm() returns true. In that case, the script does not return false, so the onSubmit function reaches the end and returns true (implicitly or explicitly), which allows the submission to continue. The record will be saved normally.
By using this pattern, any form submission that doesn’t meet our criteria will be halted unless the user confirms. You can adapt the confirmation condition and message to other scenarios (for example, requiring confirmation for deleting a record, or if certain fields have specific combinations of values). The key is that onSubmit scripts can prevent database writes when returning false, giving you a hook to enforce custom validation logic with user feedback.
Best Practices and Explanations
When implementing confirmation dialogs and other client script validations, keep in mind the following best practices:
Use onSubmit for Submission Checks: As demonstrated, an onSubmit script is ideal for validating conditions right when the user submits the form. In contrast, onChange scripts run when a field value changes and cannot reliably stop a form submit initiated by the user elsewhere (like a form Save button). Use onChange scripts for immediate field responses, but use onSubmit for anything that should potentially cancel the form submission (such as confirmation dialogs or final validations). This approach is even highlighted in ServiceNow’s documentation – onSubmit scripts are intended to validate data and can generate confirmations or abort the save if needed.
Handle Date/Time Fields Correctly: When comparing dates on the client side, always account for the user’s date format. ServiceNow provides the g_user_date_format and g_user_date_time_format variables which hold the current user’s preferred formats, and the getDateFromFormat() function to convert a date string into a numeric timestamp. Using these ensures that your comparisons work for all users (for example, one user might have dates displayed as DD-MM-YYYY and another as MM/DD/YYYY). If you attempt to directly compare date strings or manually parse them, you could run into errors or mis-comparisons.
Best Practices and Considerations
When implementing a confirmation dialog via client scripts, keep in mind the following best practices:
Use onSubmit for submission validation: As shown, an onSubmit script is the correct place to put logic that may cancel the form submission. An onChange script is not suitable for this purpose, since it doesn’t control the final submit action. ServiceNow’s documentation suggests using onSubmit scripts to validate data and potentially prompt the user (e.g., showing a confirmation for high-priority records). In general, use onChange scripts for immediate field responses, and onSubmit scripts for final validation or confirmation.
Handle date/time fields with user formats: When comparing dates client-side, always use the built-in user date format variables and parsing functions. In our example, we used g_user_date_time_format with getDateFromFormat() – this ensures the comparison logic works regardless of the logged-in user’s locale or date display preference. If you ignore these and compare raw strings or assume a format, the logic might fail for users with different date settings.
Make confirmation messages clear: Write the dialog message in a user-friendly way. It should explain why the confirmation is needed and what choosing OK or Cancel will do. For instance, our message explicitly states that pressing OK will continue with the submission and Cancel will stop it. Clear microcopy prevents confusion. (In the script above, we also called g_form.addErrorMessage() when the user cancels, to reinforce why the form didn’t submit.) Avoid vague prompts – be explicit about the consequence of each choice.
Don’t overuse confirmation dialogs: Reserve these pop-ups for important actions. If confirmations appear too frequently for trivial things, users may get habituated and click OK without reading the message, defeating the purpose. Use confirmation dialogs for cases where an irreversible or significant action is taking place (or a business rule is being bypassed). For less critical scenarios, consider alternatives like form UI hints or an “undo” mechanism rather than a constant “Are you sure?” prompt.
Always enforce rules on the server as well: Client scripts run in the browser and can be bypassed (for example, if someone uses the REST API or a malfunctioning script fails to load). For critical data integrity rules like date validations, also implement server-side logic (e.g., a Business Rule that aborts or corrects invalid data on insert/update). The client-side confirmation improves UX, but the server-side logic ensures integrity if the client script is circumvented.
Alternatives and Advanced Approaches
While the simple window.confirm() dialog in an onSubmit script is effective for many cases, there are alternative methods and scenarios to consider:
UI Action with Confirmation: If the action you want to confirm is triggered by a specific form button (a UI Action), ServiceNow provides a built-in option to require confirmation. In the UI Action record, you can set Confirmation to true and provide a confirmation message. This way, when the button is clicked, the platform will automatically show a confirmation dialog with that message before executing the action.
Custom Modal Dialogs: For a more customized user experience, you can use ServiceNow’s UI components to create modal dialogs. In the standard interface, a GlideModal (or older GlideDialogWindow) can be used to show a custom dialog with multiple buttons or richer text. In Service Portal, you can use the spModal API (e.g., spModal.confirm()) to show a styled confirmation popup. These approaches allow you to design the dialog’s look and feel and even include additional information or form inputs in the confirmation step. They require more coding (client scripts or widget scripts), but are useful for complex interactions beyond a simple Yes/No prompt.
Asynchronous Validation: In cases where the decision to allow submission requires server-side data (for example, checking a condition on the server via GlideAjax), the onSubmit script approach becomes trickier because confirm() is synchronous but GlideAjax is asynchronous. One pattern is to always return false from the onSubmit script, and within the async callback, use g_form.submit() if the user confirmed. (Another pattern is to perform validation in an onBefore Business Rule and use a field or flag to communicate back to the client, but that’s advanced and beyond our scope.) If you find yourself needing server data for confirmation, consider using a UI Action instead (which can call server code and then use alert() or other feedback for confirmation), or redesign the process to avoid a blocking confirm and use a follow-up step for confirmation.
UI Policies vs. Client Scripts: It’s worth noting that some simpler validations (like “field X must be after field Y”) could be enforced with UI Policies or native field dependencies. However, UI Policies cannot prompt the user – they can only show/hide or make fields mandatory, etc. A client script is needed for an interactive dialog. Use UI Policies for non-interactive enforcement on forms, and reserve client scripts for when you need scripting logic or interactivity that UI Policies can’t provide.
In our Change Request example, you might combine approaches: use a client onSubmit script to get user confirmation, but also have a server-side Business Rule that prevents saving if Actual Start is before Planned Start (unless some override flag is set). That way, if someone bypasses the UI, the rule still prevents bad data.
Testing and Troubleshooting
After implementing the onSubmit confirmation script, it’s important to test it and be prepared to troubleshoot if it’s not working as expected. Here are some tips:
Verify the basic functionality: Open a Change Request (or the relevant form) and try submitting data that should not trigger the confirm (e.g., Actual Start is after Planned Start). The form should save normally with no dialog. Then try the scenario that should trigger the confirm (Actual Start before Planned Start). You should see the confirmation dialog appear. Test both choices: clicking Cancel should stop the form submission (the record stays unsaved), while clicking OK should allow it to save. Also check that the Cancel path shows the error message on the form (if you included one via addErrorMessage).
Check for script errors: If the dialog isn’t showing up or the script isn’t running at all, there might be a JavaScript error preventing the script from executing. Open your browser’s developer console (in Chrome, for instance, press F12 and go to the Console tab) and watch for any error messages when you attempt to submit. A common mistake is a typo in a field name or a missing semicolon that breaks the script. Fix any errors indicated by the console and test again.
Ensure the script is active and on the correct table: It sounds basic, but make sure you saved the client script and that Active is checked. Also verify you set the correct table name and form view conditions (if any). If you only applied it to a specific view, it won’t run on other views. For broad usage, making the script Global (all views) is usually easiest.
Check UI Type (Portal vs Classic): If your users might use the Service Portal, and you want the confirmation there as well, ensure the client script’s UI Type is set to All. If it’s left as Desktop, the script will not run in Service Portal (and no confirmation will appear there). If you only care about the main platform UI, Desktop is fine.
Use logging for debugging: You can insert temporary console.log() statements in your script to output values (like the calculated plannedStartMs and actualStartMs) to the browser console, helping you see if the logic is working as intended. You can also use g_form.addInfoMessage() to show a banner on the form with debug info. Just remember to remove or comment out these debug lines when done.
Field Watcher: Another useful tool (for classic UI) is the Field Watcher. Right-click the form header > Debug > Field Watcher. This will show a sidebar logging all client script activity and field value changes. You can see if your onSubmit script runs and what it returns. It’s especially helpful if you have multiple client scripts to see the order of execution.
Multiple onSubmit scripts: If you have more than one onSubmit client script on the same table, be careful – they all execute. If any of them returns false, the submission will be stopped (even if your confirmation script returns true). Conversely, if your confirmation script returns false but another onSubmit script doesn’t account for that and still returns true, it might inadvertently allow submission. Typically, the safest approach is to consolidate logic into a single onSubmit script per form or ensure that if multiple exist, they properly check conditions so as not to conflict. (The platform will stop on the first false returned, but there’s no guarantee of execution order unless you use the Order field on the client script records.)
By following these testing tips, you should be able to confirm that your confirmation dialog works reliably. And if something goes wrong, the browser console and ServiceNow’s debugging tools will help you identify the issue.
Conclusion
Implementing a confirmation dialog on form submission in ServiceNow is a straightforward enhancement that can prevent costly mistakes and enforce business rules on the client side. In our example, we ensured that users are warned if the Actual Start date is earlier than the Planned Start date, giving them a chance to correct their input or explicitly confirm the out-of-bounds condition.
The key takeaways are:
An onSubmit client script is used to intercept the form submission. By returning false when necessary, we can abort the save operation.
The native window.confirm() function provides a quick way to prompt the user for confirmation. Its return value (true/false) can be used to decide whether to continue with submission.
Always handle data in a user-friendly and robust way – use ServiceNow’s APIs (g_form, getDateFromFormat, etc.) to ensure your script works in all scenarios, and give clear instructions to the user in the confirmation message.
After implementing, thoroughly test both paths (confirmation and cancellation) and use debugging tools to iron out any issues.
Remember that client-side confirmations complement, but do not replace, server-side validations for critical business rules.
With this confirmation dialog in place, you have added an extra safety net for your users. They can proceed with confidence, and you as a developer can ensure that data integrity is maintained without making the system feel unfriendly. This pattern can be adapted to many situations – any time you need that “second chance” prompt – and is a good tool to have in your ServiceNow development toolkit.
By following the steps and best practices outlined above, beginner and intermediate ServiceNow developers should be able to implement confirmation dialogs effectively.