Validating an Email Address
·
488 words
·
3 minutes read
Validating email addresses, like many thing, are one of those things you can put any amount of effort you want into.
The solutions range from nice’n’quick, by using regex to check the email address is formatted correctly - through to complicated, by actually trying to interface with the remote server. There are also some middle grounds available in between, like checking the top level domain has a valid MX record and detecting temporary email addresses (if these aren’t wanted). (Are there any ideas I’ve missed?)
The problem has been around since email addresses have existed.
The one sure way is to send an email to the address and have the user click on a link to confirm. But this post will look at the quicker pre-email checks first.
The Simple Version: Regex
Based on the regex by W3C, this code checks the structure of the email address.
|
|
Slightly better solution: Regex + MX Lookup
In this example, we combine the quick speed of a regex check of the email address with the slightly more dependable lookup of an MX record. This means if the domain part of the email doesn’t exist, or the domain doesn’t accept emails it will be marked as invalid.
As part of the net
package we can call on LookupMX
to do this extra lookup for us.
|
|