0

I have followed this link but it doesn't work for me. I am looking for a way to do a custom email validation that excludes some domains.

const excludedDomains = ['gmail.com', 'yahoo.com', 'live.com', 'live.co'];

const excludedEmailDomains = excludedDomains.join('|');

const VALIDATE_EMAIL = `^w+[-.w]*@(?!(?:${excludedEmailDomains}).com$)w+[-.w]*?.w{2,4}$`;

export const REG_EXP = new RegExp(VALIDATE_EMAIL, 'gm');

This doesn't want to work for me. Tests:

describe('REG_EXP', () => {
  test('should match', () => {
    const value = 'mail@company.com';

    expect(REG_EXP.test(value)).toBeTruthy(); // fails, it is false here
  });

  test('should not match', () => {
    const value = 'mail@gmail.com';

    expect(REG_EXP.test(value)).toBeFalsy();
  });
});

Only second test passes, it looks like my regexp always doesn't pass so the test result is always false.

jake-ferguson
  • 315
  • 3
  • 11
  • 32
  • Ergh, Looks like you at least twice add .com. Try to replace in your array 'google.com' to 'google' – Vasyl Moskalov Jul 26 '22 at 11:49
  • Don't use regex for email validation, this is notoriously error prone and you almost certainly will end up rejecting valid emails. Parse the email and reject the domain. The regex you've produced is *glaringly* incorrect in many ways. See https://en.wikipedia.org/wiki/International_email for example. – user229044 Jul 26 '22 at 11:56
  • You lost escaping backslashes in `^w+[-.w]*....` – Wiktor Stribiżew Jul 26 '22 at 13:00

1 Answers1

0

You have to repeat the character classes and escape the dot to match it literally, and remove the .com from the excludedDomains or else it will be there twice.

Then for the RegExp constructor double escape the backslashes.

To escape the meta characters, you can use this function.

The pattern will then look like

^\w+[-.w]*@(?!(?:gmail|yahoo|live)\.com$)\w[-.\w]*\.\w{2,4}$

Regex demo

function escapeRegex(string) {
  return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

const excludedDomains = ['gmail', 'yahoo', 'live'];

const excludedEmailDomains = excludedDomains.map(escapeRegex).join('|');

const VALIDATE_EMAIL = `^\\w+[-.w]*@(?!(?:${excludedEmailDomains})\\.com$)\\w[-.\\w]*\\.\\w{2,4}$`;

const REG_EXP = new RegExp(VALIDATE_EMAIL, 'gm');

console.log(REG_EXP);

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70