Saturday, November 23, 2013

Special Characters handling for filename in SP List

I was working with one of our client where we have developed some custom forms [Visual Web Part] which were saving the data in the SP List.
 
Problem: After go-live on the support business has reported that for some of the items they were seeing the duplicate entries for the items. After long analysis i have figured out that it is happening because business were trying to attached the files with special characters. when they tried SP was giving the error message but was not sufficient for some of the users and they were creating those items again instead of editing the already created item to only attach the file without special characters.
 
After a long discussion we agreed to prevent the user on the same form itself instead of saving it and ask user to edit it later.
 
NOTE: This is the case in OOTB SP List as well.
 
Solution:
Insert below script on your form


    function PreSaveAction() {
        var fileNames = document.getElementById('<%=hfExtensions.ClientID %>').value;
        var isInvalidFile = "";
        var attachment;
        var invalid = "no";
        var filename = "";
        var fileNameSpecialCharacters = new RegExp("[~#%&*{}<>;?/+|\"]");
        var attachmentID = document.getElementById("idAttachmentsTable");
        for (var k = 0; k < attachmentID.getElementsByTagName("span").length; k++) {

            try {
                attachment = attachmentID.getElementsByTagName("span")[k].firstChild;
                filename = attachment.data;
                for (var h = 0; h < fileNames.split(',').length; h++) {
                    if (filename.split('.')[filename.split('.').length - 1] == fileNames.split(',')[h]) {
                        isInvalidFile = "invalid";
                        break;
                    }
                }
                if (isInvalidFile == "invalid") {
                    break;
                }
            }
            catch (e) {
            }
            if (fileNameSpecialCharacters.test(filename.split('\\')[filename.split('\\').length - 1])) {
                invalid = "yes";
                break;
            }
            else {
                invalid = "no";
            }
        }
        if (isInvalidFile == "invalid") {
            alert('The file you are attempting to save or retrieve has been blocked from this Web site by the server administrators');
            return false;
        }
        else {
            if (invalid == "no") {
                return true;
            }
            else {
                alert('A file name cannot contain any of the following characters: \\ / : * ? \" < > | # { } % ~ &.Please remove the character and try again.');
                return false;
            }
        }
    }