How to check for attachment and for special characters or multiple instances of a file extension?

Leo Ruggiero
Tera Contributor

Hey all, I'm having a few difficulties checking for attachments, checking the attachments name for special characters, and checking for multiple instances of file extensions. We need to check for this due a process we have that errors out if the file name has these things. Here is the code I've put together but can't seem to get any of it working right.

 

Running this from a catalog client script so that this should work from the portal view.

 

 

function onSubmit() {
    var cat_id = g_form.getValue('sysparm_item_guid');
    var gr = new GlideRecord("sys_attachment");
    gr.addQuery("table_name", "sc_cart_item");
    gr.addQuery("table_sys_id", cat_id);
    gr.query();

    if (!gr.next()) {
        alert("You must add an attachment before submitting this request.");
        return false;
    }

    var fileName = gr.getValue("file_name");
    var specialChars = /^[a-zA-Z0-9]+$/;
    if (specialChars.test(fileName)) {
        alert("The file name contains special characters, please remove them and try again.");
        return false;
    }

    var fileExt = fileName.substr(fileName.lastIndexOf(".") + 1);
    var multipleExts = new RegExp(fileExt + "{2,}");
    if (multipleExts.test(fileName)) {
        alert("The file name contains multiple instances of the file extension, please remove them and try again.");
        return false;
    }
}

 

 

Right now the code throws a false on "You must add an attachment", regardless if there is an attachment. However I did have this portion working previously with different code but with the rest of the code it failed to check for the special characters and failed to check for the multiple instances of the file extension.

Anyone have any ideas on how I can go about this? Thanks in advance.

18 REPLIES 18

Forgive me for not seeing this sooner.  You are running the query from the client side.  When doing that, the structure of the query() call requires that you identify a function that will handle the returned data.

Hope that helps.

:{)

Helpful and Correct tags are appreciated and help others to find information faster

That won't work in an onSubmit script.  The function call is asynchronous and won't stop submitting the request.

HI Leo,

 

Thanks for the kudos.  Have you gotten everything working?  If not, what still remains open?

Hope that helps.

:{)

Helpful and Correct tags are appreciated and help others to find information faster

ricker
Tera Guru

@Leo Ruggiero,

You don't need to check for an attachment yourself, use the "Mandatory Attachment" checkbox on the item.  I'm thinking you need a ! on your if statement to run the alert when false.

Instead of running the check onSubmit you could put it in a BR on the attachment table and prevent bad named attachments from saving at all.

 

P.S. Don't use gr as a variable name!