Custom Attachment Validation for Specific File Types (.docx, .pdf) - Before Insert BR Not Working

akhilrajt
Tera Contributor

I'm working on a custom table in ServiceNow and have a requirement to restrict the file types that can be attached to a specific custom file attachment field. I only want to allow .docx and .pdf files.

 

I attempted to use a Before Insert Business Rule(BR) on the sys_attachment table to validate the file extension, but it's not working as expected.

 

My Business Rule Details:

  • Table: sys_attachment

  • When: before

  • Insert: true

  • Condition: Table name is "custom_table_name" 

  • Script: 

    (function executeRule(current, previous /*null when async*/) {

    var validExtensions = ['pdf', 'docx']; 

    var fileName = current.file_name.toLowerCase();
    var fileExtension = fileName.split('.').pop();

    if (validExtensions.indexOf(fileExtension) === -1) {

    gs.addErrorMessage('Invalid file type. For the Resume field, only the following formats are allowed: ' + validExtensions.join(', ').toUpperCase());
    current.setAbortAction(true);
    }

    })(current, previous);

 

 

  • When I attach an invalid file type (e.g., .png or .txt), the Business Rule does NOT seem to block the attachment, after choosing the file and clicking OK the browser does not respond.

 

Question: 

 

1. Is a Business Rule on sys_attachment the correct way to handle attachment validation? I suspect the timing of the attachment process might be making the before BR unreliable or difficult to use for immediate client-side feedback.

 

2. What is the recommended, best-practice approach to restrict file types for attachments in custom table?

 

 

Any guidance or alternative solutions (Client Script, Script Include, etc.) would be greatly appreciated!

 

5 REPLIES 5

Ankur Bawiskar
Tera Patron

@akhilrajt 

recently I shared solution for something similar, you can check and enhance it

you need to write onChange client script on that field and use GlideAjax with client callable script include and check file names

Not Allow Special Characters in the attachment type variable in the Service Catalog 

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@akhilrajt 

Hope you are doing good.

Did my reply answer your question?

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

hi @Ankur Bawiskar 

I'm sorry I missed the last two days, I was unexpectedly sick.

 

i tried by making few changes in the code from the above solution, tried attaching .txt file but it did not work as expected.

below are the scripts which i used.

 

client script:

 

function onChange(control, oldValue, newValue, isLoading) {
   
    if (isLoading || newValue == '') {
        return;
    }

    g_form.hideFieldMsg('resume');
   
    // Call the new function 'checkFileType'
    var ga = new GlideAjax('ValidateAttachmentFileName');
    ga.addParam('sysparm_name', 'checkFileType');
    ga.addParam('sysparam_attSysId', newValue);
   
    ga.getXMLAnswer(function(answer) {
       if (answer.toString() == 'invalid_type') {
            g_form.showFieldMsg(
                'variableName',
                'Invalid file type. Only .docx and .pdf files are allowed.',
                'error'
            );
        }
    });
}
 
 
script include:
 
var ValidateAttachmentFileName = Class.create();
ValidateAttachmentFileName.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    checkFileType: function() {
       
        var allowedExtensions = ['docx', 'pdf'];
       
       
        var sysId = this.getParameter('sysparam_attSysId');
       
        //Query the sys_attachment table
        var gr = new GlideRecord("sys_attachment");
        gr.addQuery("sys_id", sysId);
        gr.query();
       
        if (gr.next()) {
            var fileName = gr.file_name.toString();
           
           
            var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
           
           
            if (allowedExtensions.indexOf(fileExtension) == -1) {
               
                return 'invalid_type';
            } else {
               
                return 'valid';
            }
        }
       
       
        return 'valid';
    },

    type: 'ValidateAttachmentFileName'
});
 
 
 

@akhilrajt 

it worked for me.

what debugging did you do from your side?

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader