David Pham
David Pham

Reputation: 33

Check if email has a certain domain or not

I am trying to add a check to see if an email (string) is part of a specific domain in google scripts. For example, the domain would be "@company.com", so all emails with this would pass the check and emails without it won't

basically what I have is a way to retrieve the current user's email using:

var email = Session.getEffectiveUser().getEmail();

Now I want to check this email for a specific domain/company Example: [email protected]

so in this case it would be the "@companyname.com" part

I know there usually is a way to do this in other languages but how can I do this in apps script?

Upvotes: 2

Views: 1199

Answers (2)

glhr
glhr

Reputation: 4537

Here's a function which uses a regular expression to match valid e-mails, and logs the result. Note that I'm using the i flag to do a case-insensitive search:

function emailCheck(email) {
  var regExp = new RegExp("[a-z0-9\.-_]*@companyname\.com$", "i");
  match = email.match(regExp);
  if(match)
    match = true;
  else
    match = false
  Logger.log(email + ' - ' + match);
  return match
}

The following inputs:

tests = ['[email protected]','[email protected]','[email protected]']
for each (test in tests) {
    emailCheck(test);
}

Output:

[email protected] - true
[email protected] - false
[email protected] - false

Upvotes: 1

Get Off My Lawn
Get Off My Lawn

Reputation: 36351

You can test an email by using this simple regular expression:

/@company\.com$/

And with JavaScript you can use this true/false test:

/@company\.com$/.test(email)

Here is a working example:

const emailTest = email => /@company\.com$/.test(email);

['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
  .forEach(email => console.log(email.padEnd(30), emailTest(email)))

Upvotes: 0

Related Questions