[SOLVED] How to validate file name in Catalog Form's Attachment type variable?

subhadeep1618
Tera Guru

Hello Everyone,

This is not a question - rather a solution post.

Recently I was given this requirement where an uploaded file must have a certain name and extension.

e.g. "Process_Document_Template.pdf" must be the uploaded file's name.

I struggled to find the solution - but finally came up with a solution that is very simple and was right there all along, but we didn't know about this very simple concept in ServiceNow. Maybe others knew, I didn't.

 

Step-1:

Create a Script Include (client-callable class).

Then in the class, define the following method:

var FileAttachmentUtils = Class.create();
FileAttachmentUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
  /**
   * Method to read file name from attachment
   */
  readAttachmentFileName: function () {
    //Uploaded file from catalog variable
    var uploaded_file = this.getParameter("sysparm_uploaded_file");

    var gr = new GlideRecord("sys_attachment");
    if (gr.get(uploaded_file)) return gr.file_name;
  },

  type: "FileAttachmentUtils",
});

Step-2:

Create a catalog client script that will be called On Change of the Attachment variable.

NOTE: here Attachment variable means a catalog variable of Type = Attachment (not the clip-icon button).
Name of the variable is "uploaded_file" in my example - below which the field message will be shown to user.

function onChange(control, oldValue, newValue, isLoading) {
  if (isLoading || newValue == "") {
    return;
  }

  var ga = new GlideAjax("FileAttachmentUtils");
  ga.addParam("sysparm_name", "readAttachmentFileName");
  ga.addParam("sysparm_uploaded_file", newValue);

  ga.getXMLAnswer(function (answer) {
//check if the file name matches exactly what your requirements is (converting to lowercase always helps)
    if (answer.toLowerCase() != "process_document_template.pdf") {
      g_form.clearValue("uploaded_file");
      g_form.showFieldMsg(
        "uploaded_file",
        "Please rename your file as per the guidelines before uploading your attachment.",
        "warning"
      );
    }
  });
}

That's it.

Now every time a file is uploaded in the catalog form, this script will be triggered and it will validate if the attached file's name matches exactly to the prescribed requirement.

Please feel free to share if you have any better suggestion or solution than above.


Please mark this post as a solution and also as helpful, if this resolves your issue or query.

Thanks,
Subhadeep Ghosh.
0 REPLIES 0