javascript icon indicating copy to clipboard operation
javascript copied to clipboard

E-mail Validation

Open GabrielFMPinheiro opened this issue 1 year ago • 4 comments

I got a case here that the library is considering the fallowing e-mail: [email protected] invalid. I didn`t undestand the reason. Can anyone help me?

GabrielFMPinheiro avatar Mar 31 '25 17:03 GabrielFMPinheiro

Hello! I am not a contributor to this project, but I believe I can add something useful. Below is an explanation of the changes I made so that the email you provided is valid, but at the same time invalid emails are still returned as false:

  1. Improved Email Validation Regex
  2. Fixing the Access to matchedEmail: I added an extra check to ensure that the matchedEmail contains the expected values
  3. Accessing recipient and domain Properly
  4. Improved stringIsBiggerThan Function: I modified the stringIsBiggerThan function to handle cases where some of the strings might be undefined.

Please look for errors in this code. As I said, I am not a contributor or user of this repository, there is a chance that this code could break something somewhere.

Full code

const MAX_DOMAIN_LENGTH = 253;
const MAX_EMAIL_LENGTH = MAX_RECIPIENT_LENGTH + 1 + MAX_DOMAIN_LENGTH;

const validEmailRegex = /^[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+(\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // change here

const stringIsBiggerThan = (len: number, ...strs: (string | undefined)[]): boolean =>
  strs.reduce((length, s) => length + (s ? s.length : 0), 0) > len; // here too

export function isValid(email: string): boolean {
  if (!email || typeof email !== 'string') return false;

  if (stringIsBiggerThan(MAX_EMAIL_LENGTH, email)) return false;

  const matchedEmail = validEmailRegex.exec(email);
  if (!matchedEmail || matchedEmail.length < 2) return false; // here

  const [fullMatch] = matchedEmail; // annnnddddd
  const [recipient, domain] = fullMatch.split("@"); // here

  if (!recipient || !domain) return false;

  if (stringIsBiggerThan(MAX_RECIPIENT_LENGTH, recipient)) return false;
  if (stringIsBiggerThan(MAX_DOMAIN_LENGTH, domain)) return false;

  return true;
}

// Teste
console.log(isValid("[email protected]")); // true
console.log(isValid("invalid-email")); // false
console.log(isValid("[email protected]")); // true
console.log(isValid("user@toolong" + "a".repeat(250) + ".com")); // false

EnzoBernardis2007 avatar Mar 31 '25 20:03 EnzoBernardis2007

Im going to add it as part of the refactor. Ill try to follow something as zod did for their regex validation logic!

/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i

hyanmandian avatar Apr 11 '25 18:04 hyanmandian

Actual is failing too: [email protected] Enzo regex resolved

frankdors avatar May 12 '25 13:05 frankdors

Vai ser fixado na proxima versao que sera publicada em breve!

hyanmandian avatar Nov 02 '25 05:11 hyanmandian