Back to Articles

Email Validity Test - typescript snippet

2020-09-21

Source Code

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

Execution Results

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