0

What is a regular expression to validate only work email addresses in JavaScript (declining free email services such as Gmail, Yahoo, Outlook.)?

I have written the pattern = /^[^ ]+@[^ ]+.[a-z]{2,3}$/; to validate free email addresses but I don't know how to validate only work emails

Here's my code:

// validate email address
var email = document.getElementById('email');

function validateEmail() {
  var emailValue = document.getElementById('email').value;
  var pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
  if (emailValue.match(pattern)) {
    email.classList.remove("is-invalid");
  } else {
    email.classList.add("is-invalid");
  }
}

email.addEventListener('keydown', validateEmail);
Sally Ragab
  • 55
  • 1
  • 6
  • Before or after validation for the correct email address you can user JavaScripts built-in function like ``search()`` and search for like **@gmail** or **@yahoo** or any other you want to detect. – Not A Bot Mar 13 '20 at 04:16
  • The best way to validate an email address is to send an email and check the return value. Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Mar 13 '20 at 08:42

1 Answers1

1

First, you can validate that email is either correct or not.

Your logic for validation will be handling that validation.

emailValue.match(pattern)



Now if email pass the validation then use JavaScript's built-in function search() you search for free service email that you wish for.

If email has free email serive then you can reject that email.

Check below code which you can tweak around for your use case.

let email1 = "emailfortest@gmail.com";
let email2 = "emailfortest@mycompany.com";
let email3 = "emailfortest@yahoo.com";

function validateEmail(emailAddress) {
  const pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
  const notExceptedEmail = ['@gmail', '@yahoo'];
  let isFreeServiceEmailFlag = false;
  if (emailAddress.match(pattern)) {
    for(let i = 0; i < notExceptedEmail.length; i++){
       if(emailAddress.search(`${notExceptedEmail[i]}`) > -1){
         isFreeServiceEmailFlag = true;
       }
    }
    
    if(isFreeServiceEmailFlag == true)
      console.log('Cannot user free email service account');
    else
      console.log('Valid Email');
  } 
  else 
    console.log('Invalid Email');
}

validateEmail(email1);
validateEmail(email2);
validateEmail(email3);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
  • Two or three character for TLD is really short. See [TLD list](https://www.iana.org/domains/root/db) – Toto Mar 13 '20 at 08:44
  • I have found this regex that will only validate work email addresses: /^[^ ]+@[me|mac|icloud|gmail|googlemail|hotmail|live|msn|outlook|yahoo|ymail|aol]+\.[a-z]{2,3}$/ – Sally Ragab Mar 13 '20 at 17:56