最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Exceptional regex for email id validation in JavaScript - Stack Overflow

programmeradmin0浏览0评论

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 prising 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.

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 prising 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.

Share Improve this question asked May 3, 2021 at 20:15 Hybrid DeveloperHybrid Developer 2,3401 gold badge34 silver badges55 bronze badges 3
  • 2 /[a-z0-9.]{1,64}@[a-z0-9.]{1,64}/i should do the trick (inside [] brackets, . does not need to be escaped, it's a litteral character) Regex101 explanation – blex Commented May 3, 2021 at 20:17
  • 2 It's a waste of time, check the arobase, eventually a minimal length, but send an email with a confirmation link. – Casimir et Hippolyte Commented May 3, 2021 at 20:36
  • @blex Can you post this as an answer? so that I can accept. – Hybrid Developer Commented May 5, 2021 at 17:34
Add a ment  | 

2 Answers 2

Reset to default 4

/^[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

  1. Should contain exactly one @ character.

  2. Before and after @ should consist of at least 1 and at most 64 characters prising 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.

发布评论

评论列表(0)

  1. 暂无评论