Check email string is in the correct format on user input
There is an almost limitless amount of ways to validate a password string with regular expressions. This StackOverflow question has 95 answers and over 3.4 million views. The reason for this is that there is no perfect way to validate an email address ... outside of actually emailing it.
One side of this war argues for adherence to RFC5322 as closely as possible. The other side says all you need to check for is an @ with text on either side.
First, we should remember the reason we are validating email addresses in the first place. We're either:
- Assisting a customer in entering their email and not misspelling it, or;
- Validating that the email given to you is valid and this person exists.
1. User feedback and confirmation
This code has been derived from the comprehensive explanation from regular-expressions.info.
function isValidEmail(email) {
const re = new RegExp(`\A[a-z0-9!#$%&'*+/=?^_‘{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_‘{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z`);
return re.test(String(email).toLowerCase());
}
2. Back end validation
See answer #1.
You shouldn't solely use regular expressions to validate emails. Top level domains change, edge cases might emerge, and just because a provided email address is valid, that doesn't mean it exists.
- Validate the format using the above code
- Send a confirmation code and/or email to confirm ownership