Home > database >  Server side HTML Form validation?
Server side HTML Form validation?

Time:09-19

I was wondering if it is possible to validate a container bound htmlService HTML Form server-side with GAS, to prevent a User from entering Invalid Data into a sheet, for example.

If it is possible to handle the form validation server-side, how would one go about doing so?

CodePudding user response:

Google Apps Script hasn't a built-in way to do server-side form validation. You will have design the way that the form validation will be handled and how the feedback will be given to the web-app user.

A very simple validation might be to validate that the form submission has all the fields.

/**
 * Put this in a .gs file. It might be called from the client-side
code
 * by using google.script.run, using withSuccessHandler  to handle 
the boolean response.
 */
function validate(formData){
  const expectedFields = ['field1','field2'];
  const formFields = Object.keys(formData);
  const isValid = expectedFields.every(field => formFields.includes(field))
  return isValid;
}
/**
 * Call this from a form submit event on the client-side.
 * Usually this kind of code is included in a .html file between <script> tags.
 */
function handleFormSubmit(){
  google.script.run
  .withSuccessHandler(validity => {
    if(validity){
      // put here the code to confirm the that the form submission is valid
    } else {
      // put here the code to confirm the that the form submission is not valid 
    }
  })
  .withFailureHandler(error => {
    // put here the code to handle server-side errors
  }).validate(event.currentTarget)
}

There are some frameworks and communities around them that might help you on this task, i.e, Bootstrap, jQuery. Also there several are forms for sharing code like Node.js among many other that could have libraries / modules / packages that might be used with Google Apps Script.

Please bear in mind that doing server-side form validation in Google Apps Script might make your web app respond slowly as google.script.run (required for server-client communication) might be slow due to multiple factors, being one of them calling Google Apps Script services like SpreadsheetApp.

  • Related