Allow only xl sheet format as attachment for a catalog item.

Kingstan M
Kilo Sage

Hello SNC,

I want to allow only xl sheet format as attachment for a catalog item.

I wrote the below script but it seems not working. 

Any advice?

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

    //Type appropriate comment here, and begin script below

    var attachment_sys_id = g_form.getValue('attachment');

    var gsysa = new GlideRecord('sys_attachment');
    gsysa.addQuery('sys_id', attachment_sys_id);
    gsysa.query();

    while (gsysa.query()) {
        if (grsa.getValue('file_name').indexOf('.xlsx') != -1 || grsa.getValue('file_name').indexOf('.xls') != -1) {
            return true;
        } else {
            g_form.addErrorMessage("Only XL sheet can be uploaded for this catalog item");
            return false;
        }
    }

}
1 ACCEPTED SOLUTION

Mahendra RC
Mega Sage

Hello Kingstan,

Could you please check if this helps you to complete your requirement:

onSubmit Client script:

function onSubmit() {
	var recordGuid =   g_form.getUniqueValue();;
		
	var ga = new GlideAjax('CustomAttachmentUtils');
	ga.addParam('sysparm_name', 'validateAttachment');
	ga.addParam('sysparm_record_guid', recordGuid);
	ga.getXMLWait();
	var isAttachmentValid = ga.getAnswer();
	if (isAttachmentValid == "false") {
		alert('Only files with xls are allowed');
		return false;
	}
}

Create a System property:

Name: allowed.file.extension

Value: xls,xlsx

Note in this property you can put the allow file extension separated by comma in case of more than 1 extension for example xls,csv,xlsx

Script Include:

var CustomAttachmentUtils = Class.create();
CustomAttachmentUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {

	validateAttachment: function() {
        var isValid = true;
        var recordGuid = this.getParameter('sysparm_record_guid');
        var sysAttachment = new GlideRecord('sys_attachment');
	sysAttachment.addQuery('table_sys_id', recordGuid);
	sysAttachment.query();
        while (sysAttachment.next()) {
		var fileName = sysAttachment.getValue("file_name");
		var splitFileName = fileName.split(".");
		var fileExtension = splitFileName[splitFileName.length - 1];
		if (gs.getProperty("allow.file.extension").indexOf(fileExtension) == -1) {
			isValid = false;
			break;
		}
        }
        return isValid;
	}
    type: 'CustomAttachmentUtils'
});

Please mark my respsone as helpful/correct, if it answer your question.

Thanks

 

View solution in original post

5 REPLIES 5

I just wrote the exact same logic and accomplished the task. The only difference is that i did not create system property.

Final verdict for next searchers >> to accomplish file validation on catalog item. We need script include (client callable) + catalog client script (GlideAjax).