How to Avoid Item addition when attachment is invalid.

This post is a contribution from Jaishree Thiyagrajan, an engineer with the SharePoint Developer Support team

When we add a files with name containing only symbols like "([{_$%]}).txt" as an attachment to a list, we will see the error "The file/folder name that contains characters that are not allowed" & the attachment will not be added. But the item will be added.

We need to create a ItemEventReceiver and use ItemAttachmentAdding method to achieve the required functionality  

public override void ItemAttachmentAdding(SPItemEventProperties properties)

       {

           base.ItemAttachmentAdding(properties);

//write your logic to check for valid filename and cancel it out if you do not want to save the attachment.

       }

We cannot use ItemAdding event for the above requirement as we would not able to get the attachment name because the ListItem is null.