tags:

views:

406

answers:

6

I have the same expression in Javascript but it won't work in PHP for server side validation. Here's the code

if (ereg('/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+/',$_POST['email-address']))
    echo "valid email";
else
    echo "invalid email";
+3  A: 

I use the following. I also would run TRIM() on the input string before comparing it:

function is_email($string) {
  if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$string)) {
    return true;
  } else {
    return false;
  }
}
Jonathan Sampson
A: 

It could be because of the symbol you are using to concatenate the expressions (+).

Anyways you should try this one:

\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*

Raúl Roa
That's not concatenation, it means a character set must be included "once or more times".
The Wicked Flea
+10  A: 

filter which comes with PHP:

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "E-mail is not valid";

} else {

echo "E-mail is valid";

}
DMeier
I can provide you a list of valid email addresses that FILTER_VALIDATE_EMAIL says are invalid.
Erik
+7  A: 

Don't use regular expressions to "validate" email addresses

Edit: Link is broken. This is probably the right link

Gumbo
Wish I could upvote more than once. This really is a TFAQ (too frequently asked question)...
sleske
+4  A: 

use preg_match, not ereg. ereg regex strings do not use an enclosing slash character.

Also the double-backslash may not be necessary in a single-quoted string in PHP (not sure about that, though)

ʞɔıu
+1  A: 

I've now collated test cases from Cal Henderson, Dave Child, Phil Haack, Doug Lovell and RFC 3696. 158 test addresses in all.

I ran all these tests against all the validators I could find. The comparison is here: http://www.dominicsayers.com/isemail

I'll try to keep this page up-to-date as people enhance their validators. Thanks to Cal, Dave and Phil for their help and co-operation in compiling these tests and constructive criticism of my own validator.

People should be aware of the errata against RFC 3696 in particular. Three of the canonical examples are in fact invalid addresses. And the maximum length of an address is 254 or 256 characters, not 320.

Dominic Sayers