Check for valid email address


Published in: PHP 


  1. function is_valid_email($email)
  2. {
  3. if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
  4. return true;
  5. else
  6. return false;
  7. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: gdonald on January 12, 2007

The regular expression

[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+

does not compile.

When a dash is used in a character class it indicates a range.

_-. is not a valid range.

A corrected version could be

[.+a-zA-Z0-9_-]+@[a-zA-Z0-9-]+.[a-zA-Z]+

or

[-a-zA-Z0-9_.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+

When the dash is moved to the beginning or end of the character class it is automatically not part of a range and instead does a literal match on the dash character.

Here are my sample scripts:

email_bad.php:

!/usr/bin/php

email_fixed.php:

!/usr/bin/php

Posted By: gdonald on January 12, 2007

Doesn't seem to allow PHP tags. Here's another try on those sample scripts:

Here are my sample scripts:

email_bad.php:

errorreporting( EALL );

function isvalidemail( $email ) { if( pregmatch( "/[a-zA-Z0-9-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email ) > 0 ) return true; else return false; }

$emails = array( 'br0k3n', 'fred_dred@aol.com', 'fred-dred@aol.com', 'fred.dred@aol.com', 'fred+dred@aol.com' );

foreach( $emails as $email ) { echo $email . ' is' . ( isvalidemail( $email ) ? '' : ' not' ) . " valid\n"; }

email_fixed.php:

errorreporting( EALL );

function isvalidemail( $email ) { return pregmatch( '/[.+a-zA-Z0-9-]+@[a-zA-Z0-9-]+.[a-zA-Z]+/', $email ); }

$emails = array( 'br0k3n', 'fred_dred@aol.com', 'fred-dred@aol.com', 'fred.dred@aol.com', 'fred+dred@aol.com' );

foreach( $emails as $email ) { echo $email . ' is' . ( isvalidemail( $email ) ? '' : ' not' ) . " valid\n"; }

Posted By: guidorossi on January 11, 2008

Simplest way. PHP5 only

http://www.w3schools.com/php/filtervalidateemail.asp

Posted By: g0dbrz on March 5, 2008

Posted By: liorsp0 on April 15, 2008

Posted By: koncept on October 5, 2008

http://snipplr.com/view/8844/rfc822-compliant-email-address-validator/

Posted By: dominicsayers on February 26, 2009

http://snipplr.com/view/11616/rfccompliant-email-address-validator/

And check out a head-to-head of free validators here: http://www.dominicsayers.com/isemail/

Posted By: Unreal on February 28, 2009

From w3schools - http://www.w3schools.com/php/filtervalidateemail.asp

You need to login to post a comment.