Artemis | Blog | About & Contact

2019 / 11 / 03 - PHP: Bad Idea / Good Idea (raw)

E-mail validation

When a user provides an email, how can you be sure that it's a valid email?

The fact that an email is a complicated format can be a pain in the ass, because depending on how you validate the e-mail, you may leave out some users.

Now, for validation, there are two approaches: being lenient and being restrictive.

Bad idea: Using Regexes to validate an e-mail

Using a regex may be one of the most common choices to people that are unaware of problems caused with this approach.

Most regexes found on Internet have as goal to be restrictive: they'll try to match as closely as possible a "common" e-mail, producing a lot of false-negatives.

Good idea: Being lenient, and using e-mail validation instead of filtering

Before the introduction of UTF-8 in domain names, there was some well-tested methods to verify that a string matches the format of an e-mail.

For example, in PHP, the filter_var method is perfect for this need.

But with the diversity of formats, instead of being more and more restrictive, which produces a hell-ish code and more test constraints, why not be more lenient?

The concept is simple: Check that the e-mail contains two strings separated by an @, which kind of look like an e-mail, and directly send this e-mail a confirmation link.

Not only you'll verify if the e-mail is valid, but you'll also manage to check if it's an existing e-mail account!