Attachment Upload | Remove Special Characters in File Name with JavaScript

Users receive no errors and are allowed to upload whatever file name they wish. I would welcome an error - but it appears anything is allowed.

As a temporary measure, we place a disclaimer on the plumsail form for users to read before uploading attachments. We would like to add JavaScript to rename the upload and remove any special characters during the file upload process. How can I manage this with JavaScript?

We have issues removing files from the SharePoint Document Library (DL) when file names are long and/or contain certain symbols, such as [ "[email protected]#$%^()" ]. We have a Power Automate process that copies the uploaded attachment to a designated DL.

Hello @shedev,

You can either add a custom validation for the Attachments filed to force user remove special characters:

fd.field('Attachments').validators.push({
    name: 'Attachments Validation',
    error: "remove special chatacters",
    validate: function(value) {
        const spch = /[[email protected]#$%^()]+/;
        for (let i = 0; i < value.length; i++) {
            if (spch.test(value[i].name)) {
                return false
            }

            return true
        }
    }
}); 

Or replace the Attachments field with a List or Library control. This way you can rename files when they are uploaded to a document library, using the code:

var listOrLibrary = 'SPDataTable1';
var docLibraryTitle = 'DocumentLibraryName';
var docLibraryId = '2afe31be-ac14-49db-a0a8-bf8724bc8487';

fd.control(listOrLibrary).$on('filesUploaded',
    function(itemIds) {
        //get document library by Title
        var library = pnp.sp.web.lists.getById(docLibraryId);
        //go through each uploaded Item Id and set field values
        library.getListItemEntityTypeFullName().then(function(entityTypeFullName) {

            var batch = pnp.sp.web.createBatch();
            var currentName;
            var uri;


            for (var i = 0; i < itemIds.length; i++) {
                //specify which fields to update and how
                var itemId = itemIds[i];
                library.items.getById(itemId).select('FileRef', 'Id').get().then(function(item) {
                    return item

                }).then(function(item) {
                    uri = item.FileRef;
                    var fileID = item.Id;
                    filename = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf(".")).replace(/[`[email protected]#$%^&*()]/gi, '');
                    var nbatch = pnp.sp.web.createBatch();
                    library.items.getById(fileID).inBatch(nbatch).update({
                        FileLeafRef: filename
                    }, "*", entityTypeFullName)
                    nbatch.execute().then(function() {
                        fd.control(listOrLibrary).refresh();
                    });
                });
            }
        });
    });