diff --git a/Client-Side Components/Client Scripts/Client Validation of Attachments by File Type and Count/README.md b/Client-Side Components/Client Scripts/Client Validation of Attachments by File Type and Count/README.md new file mode 100644 index 0000000000..864a87ed09 --- /dev/null +++ b/Client-Side Components/Client Scripts/Client Validation of Attachments by File Type and Count/README.md @@ -0,0 +1,8 @@ +This ServiceNow client script is designed to validate file attachments on a form before submission. It's most likely used as a "Client Script" or "Client Script in a Catalog Item" that runs in the browser when a user tries to submit a form. + +This client script runs when a form is submitted in ServiceNow. It checks if the user has: + +Attached at least one file (shows an error if none). +Attached no more than three files (shows an error if more). +Only uploaded files of type PDF or PNG (shows an error for other types). +If any of these checks fail, the form submission is blocked and an appropriate error message is displayed. diff --git a/Client-Side Components/Client Scripts/Client Validation of Attachments by File Type and Count/code.js b/Client-Side Components/Client Scripts/Client Validation of Attachments by File Type and Count/code.js new file mode 100644 index 0000000000..1d18ffb059 --- /dev/null +++ b/Client-Side Components/Client Scripts/Client Validation of Attachments by File Type and Count/code.js @@ -0,0 +1,24 @@ +(function executeRule(gForm, gUser, gSNC) { + var attachments = gForm.getAttachments(); + if (!attachments || attachments.length === 0) { + gForm.addErrorMessage("You must attach at least one file."); + return false; + } + + if (attachments.length > 3) { + gForm.addErrorMessage("You can only upload up to 3 files."); + return false; + } + + var allowedTypes = ['pdf', 'png']; + for (var i = 0; i < attachments.length; i++) { + var fileName = attachments[i].file_name.toLowerCase(); + var ext = fileName.split('.').pop(); + if (!allowedTypes.includes(ext)) { + gForm.addErrorMessage("Only PDF and PNG files are allowed."); + return false; + } + } + + return true; +})(gForm, gUser, gSNC);