Tuesday 3 August 2021

Check the domain of an email address by regex

The following Google Apps Script is designed to use a regular expression (regex) to confirm if an email address domain matches one we specify eg: @hotmail.co.uk, @gmail.com, @outlook.com

I developed the code so I could screen email addresses to make sure they only came from within the institution - otherwise it would have broken the tool I was developing for creating Zoom meetings. The email addresses in this example are all stored in one cell in a Google Sheet and are separated via a comma and a single space.

Email addresses in a Google Sheet with different domains can be filtered.
Screenshot of email addresses in a Google Sheet cell

We start by getting the Google sheet., the email addresses and separating them into an array that we can loop through:

  // get spreadsheet
  var ss = SpreadsheetApp.getActiveSheet();


  // get email addresses
  var emailAddresses = ss.getRange(2, 1).getValue();


  // separate email addrresses by comma and space
  var splitEmails = emailAddresses.split(', ');

Next we have our regex which in this example will be screening our email domains against '@random.com'. We want it to be case-insensitive ('/i') and to have an end-of-string anchor so nothing can be added after the '.com' ($):

var regex = /@random\.com$/i;

Now we begin to loop through the array of email addresses, extracting each one in turn and matching it against our regex:

// loop through email addresses looking for matches
for (var i = 0; i < splitEmails.length; i++) {


  // store email address in a variable
  var emailAddress = splitEmails[i];


  // look for match against Regex
  var domainMatch = emailAddress.match(regex);

If we find a match, for the purpose of this example we will log a message, but you may choose to perform further actions such as display a popup if there is an erroneous one (as I did for my project):

// log result message
if (domainMatch) {
  Logger.log("Yes '" + emailAddress + "' matches");
}
else {
  Logger.log("No '" + emailAddress + "' does not match");
}


File Download

Download the Check the domain of an email address by regex Google Sheet here. Please use 'File' > 'Make a copy' for your own version.


No comments:

Post a Comment