Prevent Form Submission
Validate form data and prevent submission if conditions aren't met (e.g., prevent closing ticket without resolution notes).
onSubmit Table: incident
#validation #onSubmit #form-submission #prevent-save
Script Code
JavaScript
1function onSubmit() {
2 // Configuration: Define validation rules
3 var state = g_form.getValue('state');
4 var closedStates = ['6', '7', '8']; // Resolved, Closed, Cancelled
5 var requiredFields = {
6 'close_code': 'Close Code',
7 'close_notes': 'Close Notes'
8 };
9
10 // Check if ticket is being closed
11 if (closedStates.indexOf(state) !== -1) {
12
13 // Validate each required field
14 for (var fieldName in requiredFields) {
15 var fieldValue = g_form.getValue(fieldName);
16 var fieldLabel = requiredFields[fieldName];
17
18 // If field is empty, show error and prevent submission
19 if (!fieldValue || fieldValue === '') {
20 g_form.addErrorMessage(fieldLabel + ' is required when closing an incident.');
21 g_form.flash(fieldName, '#FF0000', 0); // Flash the field red indefinitely
22 return false; // Prevent form submission
23 }
24 }
25
26 // Additional validation: Check minimum length for close notes
27 var closeNotes = g_form.getValue('close_notes');
28 if (closeNotes.length < 10) {
29 g_form.addErrorMessage('Close Notes must be at least 10 characters long.');
30 g_form.flash('close_notes', '#FF0000', 0);
31 return false;
32 }
33 }
34
35 // Validation passed, allow form submission
36 return true;
37}
How to Use
1. Create an onSubmit Client Script on your table
2. Customize the validation logic for your requirements
3. Update field names and validation rules
4. Test thoroughly to ensure it works as expected
Related Scripts
Auto-populate Related Fields
Automatically populate fields when a reference field changes (e.g., populate caller's phone and email when caller is selected).
Conditional Mandatory Fields
Make fields mandatory based on the value of another field (e.g., require close notes only when state is Resolved).
Dynamic Field Visibility
Show or hide fields based on another field's value (e.g., show "Other reason" field only when user selects "Other" from dropdown).