Make attachment mandatory on Catalog item ServiceNow

Example Validation:
  • Only CSV File Type Allowed
  • Maximum of One Attachment


OnSubmit Client Script:

function onSubmit() {
var allowedExtension = '.csv';
var maxAttachments = 1;
function hasValidAttachments(elements) {
if (elements.length === 0 || elements.length > maxAttachments) {
console.log('Attachment validation failed: No attachments or too many attachments.');
return false;
}
// Attempt to retrieve file name from the first attachment element
var fileName = elements[0].getAttribute('title');
console.log('Retrieved File Name:', fileName);
if (!fileName) {
console.log('Attachment validation failed: File name is missing.');
return false;
}
// Convert the file name to lower case for case-insensitive comparison
var lowerCaseFileName = fileName.toLowerCase().trim();
console.log('Lower Case File Name:', lowerCaseFileName);
// Get the end of the file name where the extension should be
var endOfFileName = lowerCaseFileName.slice(-allowedExtension.length);
console.log('End of File Name:', endOfFileName);
// Check if the end of the file name matches the allowed extension
var isValidExtension = endOfFileName === allowedExtension;
console.log('Is Valid Extension:', isValidExtension);
return isValidExtension;
}
var attachments;
if (window == null) {
// portal
attachments = this.document.getElementsByClassName('get-attachment');
console.log('Attachments (portal):', attachments);
} else {
// native view
attachments = $j("li.attachment_list_items").find("span");
console.log('Attachments (native view):', attachments);
}
// Clear any previous error messages
g_form.clearMessages();
if (attachments.length === 0) {
g_form.addErrorMessage('Please attach at least one file.');
console.log('Error: No attachments found.');
return false;
} else if (attachments.length > maxAttachments) {
g_form.addErrorMessage('You can only upload one file. Please remove any extra attachments.');
console.log('Error: More than one attachment found.');
return false;
} else if (!hasValidAttachments(attachments)) {
g_form.addErrorMessage('The attached file must be a CSV. Please upload a valid CSV file.');
console.log('Error: Invalid file type or name.');
return false;
}
console.log('Validation passed. Form can be submitted.');
return true;
}