diff --git a/Client-Side Components/Client Scripts/validate phone number/Readme.md b/Client-Side Components/Client Scripts/validate phone number/Readme.md new file mode 100644 index 0000000000..529cd773fa --- /dev/null +++ b/Client-Side Components/Client Scripts/validate phone number/Readme.md @@ -0,0 +1,46 @@ +Phone Number Validation — Client Script (ServiceNow) +Overview + +This Client Script ensures that users enter their phone numbers in a strict format: (123) 456-7890. +It is triggered whenever the Phone field changes and validates the input in real time. + +If the input does not match the required format, the script: + +Clears the invalid value. + +Displays a field-level error message directly below the field. + +Provides a fallback alert if field-level messaging is unavailable. + +This script is designed to be user-friendly, dynamic, and failsafe. + +Features + +Validates phone numbers in the format (123) 456-7890. + +Inline error messages appear directly below the field, avoiding top-of-page clutter. + +Clears invalid input to prevent incorrect data submission. + +Works dynamically for any phone field with minimal configuration. + +Provides fallback alert for environments where inline messages are unavailable. + +Usage Instructions +1. Create the Client Script + +Navigate to System Definition → Client Scripts. + +Click New to create a client script. + +2. Configure the Script + +Name: Phone Number Validation + +Table: sys_user + +Type: onChange + +Field: phone + +Active: Checked diff --git a/Client-Side Components/Client Scripts/validate phone number/Validate PhoneNumber.js b/Client-Side Components/Client Scripts/validate phone number/Validate PhoneNumber.js new file mode 100644 index 0000000000..cf799f886f --- /dev/null +++ b/Client-Side Components/Client Scripts/validate phone number/Validate PhoneNumber.js @@ -0,0 +1,34 @@ +function onChange(control, oldValue, newValue, isLoading) { + if (isLoading || !newValue) return; + + var fieldName = control.name; + var fieldLabel = g_form.getLabelOf ? g_form.getLabelOf(fieldName) : fieldName; + + // --- Phone format: (123) 456-7890 --- + var phonePattern = /^\(\d{3}\) \d{3}-\d{4}$/; + + // Clear any existing field messages + if (g_form.hideFieldMsg) g_form.hideFieldMsg(fieldName, true); + + // Validate the phone number + if (!phonePattern.test(newValue)) { + // Reset invalid input + if (g_form.setValue) { + g_form.setValue(fieldName, ''); + } else { + control.value = ''; + } + + // Show a clear inline message below the field + if (g_form.showFieldMsg) { + g_form.showFieldMsg( + fieldName, + 'Phone Number must be in the format (123) 456-7890', + 'error', + false // false = show below the field + ); + } else { + alert(fieldLabel + ' must be in the format (123) 456-7890'); + } + } +}