Back to Freecodecamp

Challenge 67: Email Validator

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da005.md

latest2.2 KB
Original Source

--description--

Given a string, determine if it is a valid email address using the following constraints:

  • It must contain exactly one @ symbol.
  • The local part (before the @):
    • Can only contain letters (a-z, A-Z), digits (0-9), dots (.), underscores (_), or hyphens (-).
    • Cannot start or end with a dot.
  • The domain part (after the @):
    • Must contain at least one dot.
    • Must end with a dot followed by at least two letters.
  • Neither the local or domain part can have two dots in a row.

--hints--

validate("[email protected]") should return true.

js
assert.isTrue(validate("[email protected]"));

validate("[email protected]") should return true.

js
assert.isTrue(validate("[email protected]"));

validate("[email protected]") should return false.

js
assert.isFalse(validate("[email protected]"));

validate("[email protected]") should return false.

js
assert.isFalse(validate("[email protected]"));

validate("freecodecamp.org") should return false.

js
assert.isFalse(validate("freecodecamp.org"));

validate("develop.ment_user@c0D!NG.R.CKS") should return true.

js
assert.isTrue(validate("develop.ment_user@c0D!NG.R.CKS"));

validate("[email protected]") should return false.

js
assert.isFalse(validate("[email protected]"));

validate("[email protected]") should return false.

js
assert.isFalse(validate("[email protected]"));

validate("develop..ment_user@c0D!NG.R.CKS") should return false.

js
assert.isFalse(validate("develop..ment_user@c0D!NG.R.CKS"));

validate("git@[email protected]") should return false.

js
assert.isFalse(validate("git@[email protected]"));

--seed--

--seed-contents--

js
function validate(email) {

  return email;
}

--solutions--

js
function validate(email) {
  if (email.includes('..')) return false;

  const parts = email.split('@');
  if (parts.length !== 2) return false;

  const [local, domain] = parts;

  if (local.startsWith('.') || local.endsWith('.')) return false;
  if (!/^[a-zA-Z0-9._-]+$/.test(local)) return false;
  if (!domain.includes('.')) return false;

  const tld = domain.split('.').pop();
  if (tld.length < 2 || !/^[a-zA-Z]+$/.test(tld)) return false;

  return true;
}