HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Regex validation for Email Address

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
addressemailvalidationforregex

Problem

I need to validate whether my regex is correct for below scenario. Suggestion's if the regex is correct:

Wiki Link Local_part

The local-part of the email address may use any of these ASCII characters.[4] RFC 6531 permits Unicode characters beyond the ASCII range:

  • Uppercase and lowercase English letters (a–z, A–Z) (ASCII: 65–90,


97–122)

  • Digits 0 to 9 (ASCII: 48–57)



  • These special characters: ! # $ % & ' * + - / = ? ^ _ { | } ~


(limited support)

  • Character . (dot, period, full stop) (ASCII: 46) provided that it is


not the first or last character, and provided also that it does not
appear two or more times consecutively (e.g. John..Doe@example.com
is not allowed).

  • Special characters are allowed with restrictions. They are:



  • Comments are allowed with parentheses at either end of the local


part; e.g. "john.smith(comment)@example.com" and
"(comment)john.smith@example.com" are both equivalent to
"john.smith@example.com".

  • International characters above U+007F are permitted by RFC 6531,


though mail systems may restrict which characters to use when
assigning local parts.

The Regex:

^[a-z0-9][-a-z0-9.!#$%&'*+-=?^_`{|}~\/]+@([-a-z0-9]+\.)+[a-z]{2,5}$


Demo Here

Solution

I remember having read somewhere (possibly in another Code Review answer) that for an e-mail address, the simplest and most effective validation you can do is to make sure it contains an @. Making it more restrictive than that can often be a risk of invalidating some valid e-mails. You'd be surprised at some examples of valid e-mail addresses.

As an additional example, see the "almost RFC 822 compatible regex" in this answer.

Keep it simple, and don't mark some e-mail addresses that are actually valid as invalid.

email.contains("@")


If you want to be more restrictive than this, use an existing and trusted library for the validation, don't try to make another regex.

For further reading:

  • http://en.wikipedia.org/wiki/Email_address#Validation_and_verification



  • list of email addresses that can be used to test a javascript validation script on Stack Overflow



  • http://codefool.tumblr.com/post/15288874550/list-of-valid-and-invalid-email-addresses

Code Snippets

email.contains("@")

Context

StackExchange Code Review Q#55009, answer score: 35

Revisions (0)

No revisions yet.