E-mail Validation
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?
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:
- Improved Email Validation Regex
- Fixing the Access to
matchedEmail: I added an extra check to ensure that thematchedEmailcontains the expected values - Accessing
recipientanddomainProperly - Improved
stringIsBiggerThanFunction: I modified thestringIsBiggerThanfunction to handle cases where some of the strings might beundefined.
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
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
Actual is failing too: [email protected] Enzo regex resolved
Vai ser fixado na proxima versao que sera publicada em breve!