PHP

[Solved – 11 Answers] Using a regular expression to validate an email address

regex for email validation – There is a several PHP programs. Get contacted by someone that is having trouble with a site that uses it, and we end up having to make some adjustment (most recently we realized that wasn’t allowing 4-character TLDs).

For PHP, we should not use the pattern (regex for email validation) given in Validate an E-Mail Address with PHP, the Right Way.

  • That is no better than all the other non-RFC patterns. It isn’t even smart enough to handle even RFC 822, let alone RFC 5322.
  • If we need to get visualize and sophistic, implement a complete state engine. A regular expression can only act as a basic filter. The problem with regular expressions is that telling someone that their perfectly valid e-mail address is invalid (a false positive) because our regular expression can’t handle it is just offensive and impolite from the user’s perspective.
  • A state engine for the purpose can both validate and even correct e-mail addresses that would otherwise be considered invalid as it disassembles the e-mail address according to each RFC.

  • We should not use regular expressions to validate email addresses.
  • Instead, use the MailAddress class, like this:
email address code
try {
 address = new MailAddress(address).Address; } catch(FormatException
{ //address is invalid
 } 
  • The MailAddress class uses a BNF parser to validate the address in full accordance with RFC822.

why we need to validate email addresses? What is the real benefit for validating?

  • It will not catch common typos.
  • It does not prevent people from entering invalid or made-up email addresses, or entering someone else’s address.

If we need to validate that an email is correct, we have no choice than to send an confirmation email and have the user reply to that. In many cases we have to send a confirmation mail anyway for security reasons or for ethical reasons

See also  [ Solved -8 Answers ] PHP - NOW() function in PHP

  • If we need to use the regular expression, there’s two things we need to understand.
  • First, long regex for email validation make it difficult to nicely format paragraphs. So we don’t include a-z in any of the three character classes. This regex is intended to be used with our regex engine’s “case insensitive” option turned on.
  • Second, the above regex is delimited with word boundaries, which makes it suitable for extracting email addresses from files or larger blocks of text. If we need to check whether the user typed in a valid email address, replace the word boundaries with start-of-string and end-of-string anchors, like this: ^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,}$.

  • Email Regular Expression Pattern
email address code
^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*
  A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$; 
email address code
^ #start of the line
 [_A-Za-z0-9-\\+]+ # must start with string in the bracket [ ], must contains one or more (+)
 (                # start of group #1 
\\.[_A-Za-z0-9-]+ # follow by a dot "." and string in the bracket [ ], must contains one or more (+)
 )*               # end of group #1, this group is optional (*)
 @                # must contains a "@" symbol
 [A-Za-z0-9-]+ # follow by string in the bracket [ ], must contains one or more (+)
 (              # start of group #2 - first level TLD checking 
\\.[A-Za-z0-9]+ # follow by a dot "." and string in the bracket [ ], must contains one or more
 (+)
 )*            # end of group #2, this group is optional (*)
 (             # start of group #3 - second level TLD checking 
\\.[A-Za-z]{2,} # follow by a dot "." and string in the bracket [ ], with minimum length of 2
 )            # end of group #3 $ 
              #end of the line

Examples:
[email protected] gmail.com (spaces in emails) or lavanya (no domain at all) or [email protected] (no period before .com),

php validate email code
/^\[email protected]\S+\.\S+$/ 

See also  [ Solved -7 Answers ] Why doesn't this code simply print letters A to Z

Context:

email address code
^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$ 

Note: E-mail addresses that is simultaneously too strict (before the “@” character), too unclear (after the “@” character), and too negligent (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users).

The one which is used in ASP.NET by the RegularExpressionValidator.

php validate email code
^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ 

The email addresses validation using ASP.NET web application using the System.Net.Mail namespace to send emails to a list of people. So, rather than using some very complex regular expression, Simply try to create a MailAddress instance from the address. The MailAddress constructor will throw an exception if the address is not formed properly.

php validate email code
protected void emailValidator_ServerValidate(object source, ServerValidateEventArgs args) 
{ 
try 
{ 
var a = new MailAddress(txtEmail.Text); 
} 
catch (Exception ex)
{
args.IsValid = false;
emailValidator.ErrorMessage = "email: " + ex.Message; } } 

  • Use the following regex for email validation for input validation:
php validate email code
([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?(\.[0-9A-Za-z]([0-9A-Za-z-]{0,61}[0-9A-Za-z])?)+

Addresses matched by this regex for email validation:

  • Have a local part (i.e. the part before the @-sign) that is strictly compliant with RFC 5321/5322,
  • Have a domain part (i.e. the part after the @-sign) that is a host name with at least two labels, each of which is at most 63 characters long.

The second constraint is a restriction on RFC 5321/5322

  • Use the PHP build-in validation for emails.
php validate email code
filter_var($value, FILTER_VALIDATE_EMAIL) 
  • If we’re running a php-version lower than 5.3.6 please be aware of this issue: https://bugs.php.net/bug.php?id=53091
  • This article provides some of the basic informations on email address , validate email , php validate email , php email validation , email tester , email validation javascript , email validation php , php email , php form validation , emailvalidator , php validator , validation for email , form validation php , email validation regex , form validation in php , validation in php , email validation in php , regular expression for email , how to validate email in javascript , php contact form with validation , regular expression in php , email verification in php.
See also  PHP-HTTP_HOST vs. SERVER_NAME

About the author

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X