Back

Email Validity Test - typescript snippet

2021-01-01

Source Code

1const regex =
2 /^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
3
4export const isEmailValid = (email: string) => {
5 if (!email) return false;
6
7 if (email.length > 256) return false;
8
9 const valid = regex.test(email);
10 if (!valid) return false;
11
12 const parts = email.split('@');
13 if (parts[0].length > 64) return false;
14
15 const domainParts = parts[1].split('.');
16 if (domainParts.some((part) => part.length > 64)) {
17 return false;
18 }
19
20 return true;
21};
22

Execution Results

1isEmailValid('abc@def.com') === true
2isEmailValid('abc') === false
3isEmailValid('@abc.com') === false