user602403
user602403

Reputation: 11

Java scripting in SharePoint custom lists

In SharePoint lists, you are not permitted to upload files which have any kind of special characters in their file name. (For eg: file&.doc cannot be uploaded)

So I have a JavaScript code that validates the file name on submitting the list and creates a dialogue box that tells the user to rename the files before uploading and only then you can proceed.

My issue is, the code only works for 1 document, if more than 1 document is uploaded. it does not validate the second item. I need help so that I can upload n number of items and it validates eac

<Script type="text/javascript"> 
function PreSaveAction() 
{ 
var attachment; 
var filename=""; 
var fileNameSpecialCharacters = new RegExp("[~#%&*{}<>;?/+|\"]"); 
try { 
attachment = document.getElementById("idAttachmentsTable").getElementsByTagName("span")[0].firstChild; 
filename = attachment.data; 
} 
catch (e) { 
} 
if (fileNameSpecialCharacters.test(filename)) { 
alert("Please remove the special characters like ~#%&*{}<>;?/+|\ from the file attachment name and reattach the file.");
return false; 
} 
else { 
return true; 
} 
} 
</script>

Upvotes: 1

Views: 1262

Answers (3)

Justin
Justin

Reputation: 11

allow only certain files in 2007 sharepoint list

Edit: included code from comment:

<Script type="text/javascript">
function PreSaveAction()
{
    var attachment;
    var filename="";
    try
    {
        attachment = document.getElementById("idAttachmentsTable")
                             .getElementsByTagName("span")[0]
                             .fi‌​rstChild;
        filename = attachment.data;
    }
    catch (e) { }
    if (!filename.match(/^(.+?\.xlsx?)$/i))
    {
        alert("Please attach only excel files.");
        return false;
    }
    else
    {
        return true;
    }
}
</script>

Upvotes: 1

Dave Patel
Dave Patel

Reputation: 11

I created a modified version that will check for all attachments. The one liste here, only checks for the first attachment.

Here is mine

function chechAttachments() { 

var spanTag; 

var filename=""; 

var fileNameSpecialCharacters = new RegExp("[~#%&*{}<>;?/+|\"]"); 

try { 

spanTag = document.getElementById("idAttachmentsTable").getElementsByTagName("span");

for (var i = 0; i < spanTag.length; i++) {

filename = spanTag[i].innerHTML;

}

} 

catch (e) { 

} 

if (fileNameSpecialCharacters.test(filename)) { 

alert('Attachments cannot contain special characters such as "[~#%&*{<>;?/+|\"]".\n\nPlease remove the special characters from the file attachment name.');

return false; 

}  

} 

Upvotes: 0

Anthony Graglia
Anthony Graglia

Reputation: 5435

You cant loop through the list of documents? Put all the file names into a structure / Array / something and look at them all?

Upvotes: 0

Related Questions