• 3
Votes
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 190

Backtrace:

File: /var/www/stackquestions.com/public_html/application/views/question.php
Line: 190
Function: _error_handler

File: /var/www/stackquestions.com/public_html/application/controllers/Questions.php
Line: 416
Function: view

File: /var/www/stackquestions.com/public_html/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

How to validate email address using a regular expression?

Over the years I have slowly developed a regular expression that validates MOST email addresses correctly, assuming they don't use an IP address as the server part.

I use it in several PHP programs, and it works most of the time. However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized that I wasn't allowing 4-character TLDs).

What is the best regular expression you have or have seen for validating emails?

I've seen several solutions that use functions that use several shorter expressions, but I'd rather have one long complex expression in a simple function instead of several short expression in a more complex function.

Don't know about best, but this one is at least correct, as long as the addresses have their comments stripped and replaced with whitespace.

Seriously. You should use an already written library for validating emails. The best way is probably to just send a verification e-mail to that address.

  • 1
Reply Report

You should not use regular expressions to validate email addresses.

Instead, use the MailAddress class, like this:

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.

If you really want to use a regex, here it is:

 

  • 2
Reply Report