Search code examples
javascriptreactjstemplatesdocxmustache

Validate Uploaded Word Template Javascript


I am looking for a npm package or a way to access an uploaded word .docx file client side in a browser. I want to validate the user's .docx file that will be compared to an array of variables (thats dynamically created) to confirm that the .docx file has all of the variables in use.

The preferred method is to upload the .docx, access the content of the docx clientside, and search for the variables (format for the template variables will be mustache "{{ }}" ) on the clientside, before submitting the form to the server.

An example would be similar to this.


WORD DOCX

"My name is {{ name }} and I love {{ sport }}. I also love enjoying {{ food }} with a glass of {{ drink }}."


const templateVariables = ["name","sport","food","beer"];

NOTIFICATION* The template you have uploaded does not use the variable "beer".

NOTIFICATION* The template you uploaded contains an extra variable "drink".


The main objective is to be able to either access the body content of an uploaded .docx in a form via the client side. I have comparison code in place to handle that part, Im just having trouble getting the content of the file to have something to compare too.


Solution

  • If i understand you right you need code to read docx file content in the client? Here it is.

    <html>
      <head>
        <meta charset="utf-8" />
        <title>title</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.19.5/docxtemplater.js"></script>
        <script src="https://unpkg.com/[email protected]/dist/pizzip.js"></script>
      </head>
      <body>
        <input type="file"></input>
        <script>
          const input = document.querySelector("input[type=file]")
          input.addEventListener("change", () => {
            const reader = new FileReader();
            reader.onload = (e) => {
              const content = e.target.result;
              const zip = new PizZip(content);
              const doc = new docxtemplater().loadZip(zip)
              const text = doc.getFullText();
              alert(text);
            };
            reader.readAsBinaryString(input.files.item(0));
          });
        </script>
      </body>
    </html>