Validate e-mail address with regular expression

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

All regular expressions start and end with forward slashes to differentiate them from ordinary string expressions. Most regular expressions start matches at the first character ^ and end at the last $.

Now we try to match the mailbox name which can include periods and dashes \w+ states one or more alphanumeric must be at the start of the name. ([\.-]?\w+)* allows periods or dashes to be included in the mailbox name with the trailing \w+ ensuring that those characters can not finish the name. The @ is the mandatory separator.

The domain name can have several .xx or .xyz suffixes such as .com.uk. Once again \w+ ensures that domain starts with an alphanumeric and ([\.-]?\w+)* allows for the dashes and periods. Finally (\.\w{2,3})+ ensures that there is at least one suffix of between 2 and 3 characters preceded by a period.

Note: This is not a completely foolproof validation as it does not account for new domain names of 4 or more characters. Also not all two and three letter combinations are legitimate domains!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.