Create a Library in Google Apps Script

When Google Apps Script was first launched it was tiresomely necessary to copy and paste code between projects. Thankfully, we can these days create a library of useful code and access it from (or share it for use in) other projects just by referencing the project’s key.

In this post I’m going to present a trivially simple library to validate the formats of certain data using regex (regular expression) statements (I talked about regex in an earlier post).

The library will have just one function, which will check that a given string corresponds to one of three formats: a valid email address, a format I’ve called name (2-30 alphanumeric characters or spaces) or a format I’ve called username (1 to 20 alphanumeric characters or underscore). Here’s the code:

function isValidFormat(text, format) {
var testformat;
switch(format) {
   case "email": // email address
      testformat = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
      break;
   case "name": // 3 to 20 alpha characters or spaces
      testformat = /^[A-Za-z0-9 ]{3,20}$/;
      break;
   case "username": // 1 to 20 alpha characters or underscore
      testformat = /^[A-Za-z0-9_]{1,20}$/;
      break;
   default:
      testformat = "";
 }
if ((testformat == "")||(!testformat.test(text))) {
   return false;
 }
 
 return true;
 
}

Here’s the code in a Script editor session:

Click image to enlarge

Click image to enlarge

I want to save this code as a library so I can use it in other projects. I’ve called my script valid, which will become the default name for the library. Firstly I use File > Manage Versions to save a version of my library:

Click image to enlarge

Click image to enlarge

Now I need to get the Project Key. For this I’m going to use File > Project Properties from the top menu:

Click image to enlarge

Click image to enlarge

From the pop-up dialog I can copy the Project key to the clipboard:

Click image to enlarge

Click image to enlarge

Now in my new project, in which I intend to use the library, I can go to Resources > Libraries… from the menu …

Click image to enlarge

Click image to enlarge

… and paste the project key:

Click image to enlarge

Click image to enlarge

If more than one version of the library is available, I can select the one I want using the drop-down selector. Having made my selection and confirmed by clicking Save, the library is now included, and all its functions can be called in code by using the function name preceded by the library name and a dot:

Click image to enlarge

Click image to enlarge

Finally, here it is in action, checking the validity of the data in a spreadsheet column:.

Click image to enlarge

Click image to enlarge

Documenting the library correctly using JSDoc will be covered in a future post.