Making Fields Required in this Google Forms Submitter Script

Making Fields Required in this Google Forms Submitter Script

Hi, I came across the following script - and it's been awhile since I looked at and don't remember where I came up on it. GitHub I believe. At any rate, I was revisiting it and I need some help.

The form submissions work. When someone fills out the form results go to the Google Form as anticipated. However, none of the fields are currently required.

That's what I need help with. Where in the following script would I check if certain fields were filled out and report back to the user on submit? And what would be the template code to use to accomplish this?

None of the validEmail functionality that's currently in the script seems to do anything as I can put 'blah' in the email  field and it submits w/o error.

Thanks!

  1. (function() {
  2.   function validEmail(email) {
  3.     var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
  4.     return re.test(email);
  5.   }

  6.   function validateHuman(honeypot) {
  7.     if (honeypot) {  //if hidden form filled up
  8.       console.log("Robot Detected!");
  9.       return true;
  10.     } else {
  11.       console.log("Welcome Human!");
  12.     }
  13.   }

  14.   // get all data in form and return object
  15.   function getFormData(form) {
  16.     var elements = form.elements;

  17.     var fields = Object.keys(elements).filter(function(k) {
  18.           return (elements[k].name !== "honeypot");
  19.     }).map(function(k) {
  20.       if(elements[k].name !== undefined) {
  21.         return elements[k].name;
  22.       // special case for Edge's html collection
  23.       }else if(elements[k].length > 0){
  24.         return elements[k].item(0).name;
  25.       }
  26.     }).filter(function(item, pos, self) {
  27.       return self.indexOf(item) == pos && item;
  28.     });

  29.     var formData = {};
  30.     fields.forEach(function(name){
  31.       var element = elements[name];
  32.       
  33.       // singular form elements just have one value
  34.       formData[name] = element.value;

  35.       // when our element has multiple items, get their values
  36.       if (element.length) {
  37.         var data = [];
  38.         for (var i = 0; i < element.length; i++) {
  39.           var item = element.item(i);
  40.           if (item.checked || item.selected) {
  41.             data.push(item.value);
  42.           }
  43.         }
  44.         formData[name] = data.join(', ');
  45.       }
  46.     });

  47.     // add form-specific values into the data
  48.     formData.formDataNameOrder = JSON.stringify(fields);
  49.     formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
  50.     formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default

  51.     console.log(formData);
  52.     return formData;
  53.   }

  54.   function handleFormSubmit(event) {  // handles form submit without any jquery
  55.     event.preventDefault();           // we are submitting via xhr below
  56.     var form = event.target;
  57.     var data = getFormData(form);         // get the values submitted in the form

  58.     /* OPTION: Remove this comment to enable SPAM prevention, see README.md
  59.     if (validateHuman(data.honeypot)) {  //if form is filled, form will not be submitted
  60.       return false;
  61.     }
  62.     */

  63.     if( data.email && !validEmail(data.email) ) {   // if email is not valid show error
  64.       var invalidEmail = form.querySelector(".email-invalid");
  65.       if (invalidEmail) {
  66.         invalidEmail.style.display = "block";
  67.         return false;
  68.       }
  69.     } else {
  70.       disableAllButtons(form);
  71.       var url = form.action;
  72.       var xhr = new XMLHttpRequest();
  73.       xhr.open('POST', url);
  74.       // xhr.withCredentials = true;
  75.       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  76.       xhr.onreadystatechange = function() {
  77.           console.log(xhr.status, xhr.statusText);
  78.           console.log(xhr.responseText);
  79.           var formElements = form.querySelector(".form-elements")
  80.           if (formElements) {
  81.             formElements.style.display = "none"; // hide form
  82.           }
  83.           var thankYouMessage = form.querySelector(".thankyou_message");
  84.           if (thankYouMessage) {
  85.             thankYouMessage.style.display = "block";
  86.           }
  87.           return;
  88.       };
  89.       // url encode form data for sending as post data
  90.       var encoded = Object.keys(data).map(function(k) {
  91.           return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
  92.       }).join('&');
  93.       xhr.send(encoded);
  94.     }
  95.   }
  96.   
  97.   function loaded() {
  98.     console.log("Contact form submission handler loaded successfully.");
  99.     // bind to the submit event of our form
  100.     var forms = document.querySelectorAll("form.gform");
  101.     for (var i = 0; i < forms.length; i++) {
  102.       forms[i].addEventListener("submit", handleFormSubmit, false);
  103.     }
  104.   };
  105.   document.addEventListener("DOMContentLoaded", loaded, false);

  106.   function disableAllButtons(form) {
  107.     var buttons = form.querySelectorAll("button");
  108.     for (var i = 0; i < buttons.length; i++) {
  109.       buttons[i].disabled = true;
  110.     }
  111.   }
  112. })();