Posted By

tylerhall on 11/30/-1


Tagged

regex email valid


Versions (?)

Who likes this?

327 people have marked this snippet as a favorite

arcturus
Bunker
College
theferf
mrm52
luxuryluke
designerd
katxorro70
FReigM
terriK
px
yuconner
irdial
olive
oronm
NexusRex
ttscoff
clifton
raws
blakeb
Hollow
dmarten
demods
noname
banjomamo
Phoenix
alexd0001
bitcrumb
fael
rich13
edwinjanmoss
vali29
hudge
copyleft
motoroller
dobbshead
marteki
verbal
vilebender
wirjo
adamweeks
madrid
mbcdg
jeff
raptrex
emuman
JimiJay
cschlens
xsubodh
cristianciofu
sosof
SpinZ
Firemarble
dyesin
adamsimms
thebrokenlight
eorwoll
paullorentzen
ibomb
mrjthethird
Arzakon
skywalker
zeusmedia
haozi
romanos
jamarama
Alshie
gAmUssA
mmccrack
stasiaholdren
unabatedshagie
blackabee
shii
dopple
fsorbello
pablodgavilan
jamesming
tikitakfire
jsalo
crashdr
amxm
sumandahal
darkapple
jfherring
oriolfb
hans
Leech
shameel
grassdog
Shocm
Wiederkehr
rubensarrio
ahjo
meetneps
joaosalless
juansierra
salibaray
iconsis
jackii
baqc
carlosabargues
LostCore
justinscheetz
Hilyin
joelataylor
yuindustries
brother_maynard
vevhlos
elbuenob
PapTom
polarbear
windmarble
matthall
owais
cornellsteven
Anber
willwish
nreliu
novatvstdios
irishsk
hamiltonmascioli
Triconium
g0mer
thadwheeler
Zaphod_42
fragmentist
ozone
nb109
delarge
Nanobyte
metallic07039
gripnrip
thatryan
eapen
Blux
JustGreg
obsessivejosh
bjhs
maxvee8
unitechy
calvingilbert
NyX
joet3ch
aha0617
mailstefsteide
tandouri
GrillPhil
rene-design
zartgesotten
codearachnid
jweagley
KF
Gr33d
Blacksnipe
buk
mattnews
palimadra
kellyrmartin
ruhanirabin
shabbar
debagel
risico
cindreta
achilles283
ckayra
franverona
portalpie
eivind
metoikos
dfaulty
bradless
jaff
larste
benrudolph
LyndseyPearce
leecsargent
webalienz
jkjeldgaard
sandynata
Trinovantes
hades985
d55beck
kaartz
phil7085
yves
kwanhon
jofalltrades
sethetter
sonnh
joaofgf
htl
NARKOZ
ofadlaoui
osirisinternet
sree01
iamadams
giuliom
lolindirfaelivrin
Swift-R
sxnc
mgerdt
all3n
ATLChris
pytheas
jimridge
daubu
pchengsf
techdetours
naeemnur
johnamiahford
yauuik
fauverism
athanassiadis
fernandojmartin
gnitter
pinyeiro
cjmling
adrianspiegel
seanpowell
bobbym245
vkolev
armanx
gavatron
dext
kuchenfari
bigfish
bindaskhan2004hotmailcom
lifewishes
zachdunn
poet
sherlack
pablo808
connorjackson
claudiowebdesign
vaskointeractive
0leg
williamsOwen
RvDesigns
broikmann
jarod51
arsha
tspitzr
aegony
garthhumphreys
dwenaus
creativeboulder
kijtra
CyKy
bdiddymc
intothelight
NeekGerd
thegnobo
silverskymedia
metthyn
dubogii
avinash2
anhonestboy
luckystokes
julianrhyswilliams
djsoftlayer
wearefreya
germanny
prit
rajashri78
logiq
qubestream
benediktvaldez
Corncrib
jumichot
dayseye49
merritt212
18zehn
Ideandro
MadRukus
Briantjuh
xhiena
nerdfiles
ban17
rlynch3
XjSv
fjckls
depiction
meetzah
DesignGoggles
svemoguci
geek4evr
TomasBerckx
gregorynicholas
fengelz
kript
tanveer
timr
RainyDayMedia
sharktale
tralston
mr2p
rweng
jasonlindberg
masta
andrey
White
bug5
speckledjim
rookie68
owenbot
dhargan
rmethod
clac
tonysgi
jaggermeister
mister
jaythakar

candicom
tbsommerkamp
hugohs
erikgeerling
mabad86
dendaak
ekarakas
gecube
imoddesign
3polars
shuraki
RicardoMedina
supupoff
henrymcc


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', '[email protected]', '[email protected]', '[email protected]', '[email protected]' );

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', '[email protected]', '[email protected]', '[email protected]', '[email protected]' );

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

Posted By: bucabay on September 3, 2009

To check whether an email address actually exists on the mailserver, use the [PHP SMTP Email Validation][1] class.

[1] http://code.google.com/p/php-smtp-email-validation/ "PHP SMTP Email Validation"

Posted By: bucabay on September 3, 2009

The correct link:

To check whether an email address actually exists on the mailserver, use the PHP SMTP Email Validation class.

Posted By: svenito on September 30, 2009

Simplified reg ex for this: /\S+@\S+.\D+/

Posted By: hm2k on December 21, 2009

Try this: validemail.org

Posted By: ginoplusio on December 27, 2009

Here is another SMTP mail validation function in php: http://snipplr.com/view/25505/validate-emails-with-smtp-and-php/

Posted By: Masis on February 9, 2010

You can try the next: function checkemailaddress($email) { // First, we check that there's one @ symbol, // and that the lengths are right. if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters // in one section or wrong number of @ symbols. return false; } // Split it into sections to make life easier $emailarray = explode("@", $email); $localarray = explode(".", $emailarray[0]); for ($i = 0; $i < sizeof($localarray); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_{|}~-][A-Za-z0-9!#$%& ↪'*+/=?^_{|}~.-]{0,63})|(\"[^(\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } // Check if domain is IP. If not, // it should be valid domain name if (!ereg("^[?[0-9.]+]?$", $email_array[1])) { $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])| ↪([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; }

Also you can search for demo email php form and look a right code

Posted By: darksider on April 30, 2010

apart from the little typos/errors noted by the others, this is a great snippet. Short, Sweet, and very useful. thanks and good work, dude - keep it up!!

-darksider-

Posted By: jfherring on June 19, 2010

http://www.snipplr.com/view/10897/valid-email-address-filter/

Posted By: Calvista on September 16, 2010

+1 for @jfherring

Posted By: housecor on October 26, 2010

The code is unnecessarily verbose. There's no need to explicitly return true/false with an if/else. This body will suffice:

return (pregmatch("/[a-zA-Z0-9-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0);

Posted By: NaRzY on November 4, 2010

Way too much of an overkill. You should be using PHP's filter_var. Example below:

Posted By: NaRzY on November 4, 2010

if(!filtervar($email, FILTERVALIDATE_EMAIL)) { // Error message here }

Posted By: Scriptor on December 14, 2010

@NaRzY - that code is nearly 3 years old.

Posted By: alyssonweb on December 14, 2010

there is no reason to use if/else statement you can simply return preg_match(); http://snipplr.com/view/45702/check-for-valid-email-address-rfc/

Posted By: alyssonweb on December 16, 2010

http://snipplr.com/view/45716/check-for-valid-email-address-rfc/

Posted By: asdasDan on January 5, 2011

As many have noted, using custom regular expressions isn't necessary when filter_var options are available.

+1 to housecor as well.

Posted By: MikeNGarrett on February 18, 2011

filtervar($email, FILTERVALIDATE_EMAIL);

This either returns the email or false.

Posted By: Jotape on August 31, 2011

http://www.snipplr.com/view/58338/validate-email-and-domain/

Posted By: mladoux on April 21, 2012

http://snipplr.com/view/40841/email-validation-ipv6-version/ && http://snipplr.com/view/40842/email-validation-ipv4-version/

both would do a better job, however, unless you are forced due to legacy reasons, I would use php's built in filtervar() --> http://us.php.net/manual/en/function.filter-var.php ( some people are still running pre 5.2 versions of php )

Posted By: squadsupply on May 16, 2012

you should also check for a valid DNS

function validate_email($email){

$exp = "^[a-z\'0-9]+([.-][a-z\'0-9]+)*@([a-z0-9]+([.-][a-z0-9]+))+$";

if(eregi($exp,$email)){

  if(checkdnsrr(array_pop(explode("@",$email)),"MX")){
    return true;
  }else{
    return false;
  }

}else{

  return false;

}
}

Posted By: rafanake on March 29, 2014

function isvalidmail($email) { return filtervar($email, FILTERVALIDATEEMAIL) && checkdnsrr(arraypop(explode("@", $email)), "MX") ? true : false; }

Posted By: rafanake on March 29, 2014

function isvalidmail($email) { return filtervar($email, FILTERVALIDATEEMAIL) && checkdnsrr(arraypop(explode("@", $email)), "MX") ? true : false; }

You need to login to post a comment.