This is a JavaScript translation of the validation suggested by the official Rails guide used by thousands of websites:
/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
Relatively simple but tests against most common errors.
Tested on a dataset of thousands of emails and it had zero false negatives/positives.
Example usage:
const emailRegex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
emailRegex.test('[email protected]'); // true
// Multi-word domains
emailRegex.test('[email protected]'); // true
emailRegex.test('[email protected]'); // true
// Valid special characters
emailRegex.test('unusual+but+valid+email1900=/!#$%&\'*+-/=?^_`.{|}[email protected]') // true
// Trailing dots
emailRegex.test('[email protected].'); // false
// No domain
emailRegex.test('email@example'); // false
// Leading space
emailRegex.test(' [email protected]'); // false
// Trailing space
emailRegex.test('[email protected] '); // false
// Incorrect domains
emailRegex.test('email@example,com '); // false
// Other invalid emails
emailRegex.test('invalid.email.com') // false
emailRegex.test('invalid@[email protected]') // false
emailRegex.test('[email protected]') // false