1

I am working on a "deploy as a web app - Google Apps Script". The script uses the 'html service'. My sample script does write data to a Google Sheet but I hope to do more with your help.

  1. I want to check to make sure the email value contains a valid email pattern 2. I want to only save data to the spreadsheet if it is a valid email pattern.

My failed attempt to accomplish this is listed below... the spreadsheet key is not valid.

Code.gs below

var submissioSSKey = '1xjsrUJaPxxxxlpxxtf_hoSYw6tkr4WzbEIHTrB6ysx4';
function doGet() {
   return HtmlService
      .createTemplateFromFile('index')
      .evaluate()
     .setSandboxMode(HtmlService.SandboxMode.IFRAME);

}

function processForm(myForm) {
  var email = myForm.email;
  var ss = SpreadsheetApp.openById(submissioSSKey); 
  var sheet = ss.getSheetByName('Data');

  sheet.getRange(sheet.getLastRow()+1, 1, 1, 2).setValues([[Date(), email]]);  
  }

index.html below

    <script>
function DataSaved(){    
  var emailPattern = /^[a-zA-Z0-9._]+[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/;
  if (emailPattern.myForm(email) == false) {
         document.getElementById('submitMessage1').innerHTML = "* a valid email is required";
}

  // document.getElementById("myForm").reset();  // Reset

    return false; // Prevent page refresh

};
 </script>

<style>
body {
    background-color: #000;
}

.container {
width:800px;
    margin:0px auto;
    text-align:left;
    padding:15px;
    border:1px dashed #333;
    background-color:#ccc;
}

p {
  color: red;
}

#title {
  font-size: 1.3em;
  line-height: 50%;
  color: #fff;
  text-align: left;
  font-weight: bold;
  margin: 0px;
  margin-bottom: 10px;
}

label {
    color: #fff;
}
</style>

<div class="container">
<br /><div id="title">Simple Form</div><br />
<form id="myForm">
<label>Email</label> <br />
<input type="text"   tabindex="1"  id="email" name="email" size="25" required/>
<div id="submitMessage1"></div><br /><br />
<br /><br />
<input type="button" tabindex="2"  id="Submit" value="Submit"  
  onClick="google.script.run.withSuccessHandler(DataSaved).processForm(this.form)"/>
</form>
</div>

Regards,

Chris

Chris S
  • 225
  • 1
  • 5
  • 15

2 Answers2

1

Right now, the code for the onclick event is inside the input element:

<input type="button" tabindex="2"  id="Submit" value="Submit" onClick="google.script.run.withSuccessHandler(DataSaved).processForm(this.form)"/>

And the check for the correct email format isn't done until form data is sent to the server. I'd change the flow of the code. Call a function in the HTML script tag first, then if the email format passes, use the google.script.run API to send the form data to the server.

<input type="button" tabindex="2"  id="Submit" value="Submit" onClick="validateEmailFormat(this.form)"/>

Script Tag

<script>
  function validateEmailFormat(argFormObject){
    var email = myForm.email;
    var emailPattern = /^[a-zA-Z0-9._]+[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/;
    if (emailPattern.myForm(email) === false) {
      document.getElementById('submitMessage1').innerHTML = "* a valid email is required";
    } else {
      google.script.run
        .withSuccessHandler(DataSaved)
        .processForm(email)

    };
  };

  function DataSaved() {
    document.getElementById('submitMessage1').innerHTML = "The email was saved"; 
  };
</script>

Code.gs

function processForm(argEmail) {
  var ss = SpreadsheetApp.openById(submissioSSKey); 
  var sheet = ss.getSheetByName('Data');

  sheet.getRange(sheet.getLastRow()+1, 1, 1, 2).setValues([[Date(), argEmail]]);  
}

This code gets the email out of the form object in the script tag before sending it to the server. No point in sending the entire form object to the server if all you need is the email value.

Alan Wells
  • 30,746
  • 15
  • 104
  • 152
  • Sandy, I put your code in the project. Nothing is written to the spreadsheet and I receive no messages when I type a good or a bad email. I think I found a typo in the email pattern portion of the code "emailPattern.myForm(email) === false)" I think should have two == instead of three? Changing that; didn't resolve the issue. I am wondering if the issue might be the calling of the 'email' example "emailPattern.myForm(email)" might not be the proper way to evaluate the 'email' field value. I don't know, maybe I need to recheck what you sent me... I probably messed it up when pasting. – Chris S Apr 19 '15 at 02:26
  • Open up the browser console and see if there are any errors there. You can add some `console.log('your message here')` statements to the HTML script functions to debug how far the code is getting, and what the results are. You can also comment out the email pattern check to see of the rest of the code is working. My answer was focusing on the program flow, and I didn't check the regEx. – Alan Wells Apr 19 '15 at 02:44
  • I have been working with your program flow example and I think it will work perfectly once I figure out the details on how to make the 'validateEmailFormat' function work like I wanted. – Chris S Apr 19 '15 at 15:33
  • I'm sure there are lots of posts about validating the email. [StackOverflow Post validate email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Alan Wells Apr 19 '15 at 15:48
1

I have the main concepts of validating Google Apps Script form data using Google's 'html service'and writing to a Google Spreadsheet in working code thanks to Sandy. My working code might be useful to others so I am posting the code here. You will need to replace the 'submissioSSKey' value with the value in your spreadsheet url to make this work. You will also need to run doget and accept permissions.

code.gs should look like this

var submissioSSKey = '1xjsrUJaPxxxxlpxxtf_hoSYw6tkr4WzbEIHTrB6ysx4';
function doGet() {
   return HtmlService
      .createTemplateFromFile('index')
      .evaluate()
     .setSandboxMode(HtmlService.SandboxMode.IFRAME);

}

function processForm(myForm) {
  var email = myForm.email;
  var ss = SpreadsheetApp.openById(submissioSSKey); 
  var sheet = ss.getSheetByName('Data');

  sheet.getRange(sheet.getLastRow()+1, 1, 1, 2).setValues([[Date(), email]]);  
  }

index.html should look like the following

<script>

function validateEmailFormat(argFormObject){
    console.log('start')
    var emailEntry = document.forms["myForm"]["email"].value;
  if (emailEntry.length == 0) {
      document.getElementById('submitMessage1').innerHTML = "* a valid email is required";
    } else {      
      google.script.run
        .withSuccessHandler(DataSaved)
       .processForm(myForm)
    }
  };

  function DataSaved() {
    document.getElementById('submitMessage1').innerHTML = "The email was saved"; 
  };

 </script>

<style>
body {
    background-color: #000;
}

.container {
width:800px;
    margin:0px auto;
    text-align:left;
    padding:15px;
    border:1px dashed #333;
    background-color:#ccc;
}

p {
  color: red;
}

#title {
  font-size: 1.3em;
  line-height: 50%;
  color: #fff;
  text-align: left;
  font-weight: bold;
  margin: 0px;
  margin-bottom: 10px;
}

label {
    color: #fff;
}
</style>

<div class="container">
<br /><div id="title">Simple Form</div><br />
<form id="myForm">
<label>Email</label> <br />
<input type="text"   tabindex="1"  id="email" name="email" size="25" required/>
<div id="submitMessage1"></div><br /><br />
<br /><br /> 
  <input type="button" tabindex="2"  id="Submit" value="Submit" onClick="validateEmailFormat(this.form)"/>
</form>
</div>
Chris S
  • 225
  • 1
  • 5
  • 15