Hybrid Developer
Hybrid Developer

Reputation: 2340

Exceptional regex for email id validation in JavaScript

What could be the Regex for accepting .@. as a valid email id? Also need to check the below conditions.

  1. Should contain exactly one @ character.

  2. Before and after @ should consist of at least 1 and at most 64 characters comprising only letters, digits and/or dots(a-z, A-Z, 0-9, .).

was trying with \b[\w\.-]+@[\w\.-]+\.[\w]{0,0} but not working as expected.

Upvotes: 1

Views: 9369

Answers (2)

blex
blex

Reputation: 25634

/^[a-z0-9.]{1,64}@[a-z0-9.]{1,64}$/i should do the trick (Regex101 explanation):

function demo(str) {
  const isEmail = /^[a-z0-9.]{1,64}@[a-z0-9.]{1,64}$/i.test(str);
  console.log(isEmail, str);
}

demo('.@.'); // OK
demo('[email protected]'); // OK
demo('a-b_c@a_b'); // Bad chars
demo('a.b.c'); // No @
demo('1234567890123456789012345678901234567890123456789012345678901234@a'); // OK
demo('12345678901234567890123456789012345678901234567890123456789012345@a'); // Too long

Upvotes: 4

Olian04
Olian04

Reputation: 6872

  1. Should contain exactly one @ character.

  2. Before and after @ should consist of at least 1 and at most 64 characters comprising only letters, digits and/or dots(a-z, A-Z, 0-9, .).

You don't need regex for that:

const validateEmail = (email) => {
  const parts = email.split('@');
  if (parts.length !== 2) {
    // Either no @ or more than one
    return false;
  }
  const [before, after] = parts;
  return (
    before.length > 0 && 
    before.length <= 64
  ) && (
    after.length > 0 && 
    after.length <= 64
  );
}

console.log(
  validateEmail('.@.'),
  validateEmail('[email protected]'),
  validateEmail('wrong@'),
  validateEmail('this@is@wrong'),
);

Using regex would be overkill, and will likely be a lot slower than performing 1 split, and 3 equality checks.

Upvotes: 0

Related Questions