[Your IP: 54.81.117.119]
Logowanie

Język: PL EN

KySoft Systemy Informatyczne


sitemap

PHP/HTML tips & tricks

email-validator
html-entities
http-build-str
inline-sms-orange
inline-youtube
mathjax-equations
rss-howto
skype-hidden-emots
syntax-highlight
text-highlight
world-flags
(currently only in english)

Validating e-mail syntax


Email address validation is quite more complex than it might look at first
since RFC 5322 defines quite large set of characters to be used in email address.
See also Cal's article on parsing mail

Part of RFC 5322 (sec.3) in BNF-like syntax:
addr-spec       =   local-part "@" domain
local-part      =   dot-atom / quoted-string / obs-local-part
domain          =   dot-atom / domain-literal / obs-domain
domain-literal  =   [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
dtext           =   %d 33-90 /         ;  Printable US-ASCII
                    %d 94-126 /        ;  characters not including
                    obs-dtext          ;  "[", "]", or "\"
quoted-string   =   [CFWS]
                    DQUOTE *([FWS] qcontent) [FWS] DQUOTE
                    [CFWS]
where:
quoted-pair     =   ("\" (VCHAR / WSP)) / obs-qp
FWS             =   ([*WSP CRLF] 1*WSP) /  obs-FWS

basic solution
function is_email($str){
	$re="\w+([.+-]\w+){0,4}@\w+([.-]\w+){1,3}";
	if (preg_match("/^".$re."$/i",$str)) return 1;
	return 0;
}
function test:
Matches: name.surname@blah.com=1 | "b. blah"@blah.co.nz | a@a.com=1 | a@a.com.au=1 | a@a.au=1 | example@example.com=1 | foo@bar.info=1 | blah@127.0.0.1=1 | e@eee.com=1 | eee@e-e.com=1 | abc@def.gh=1 | a+b_c@d-e_f.gh=1 | abc@def.ghijkl=1 | foo+bar!@example.com
Not matches: name surname@blah.com | name."surname"@blah.com | name@bla-.com | .@eee.com | eee@e-.com

much better solution
function is_email($str){
	$re="\w+([.+-]\w+){0,4}@\w+([.-]\w+){1,3}";       //simple match
	$quoted="\"[\w+-. ]+\"@\w+([.-]\w+){1,3}";        //match quoted
	$lc="\w,!#$%&'*+\-\/=?^_`{|}~";                   //local-part (before @) chars
	$other="[$lc]+(\.[$lc]+){0,4}@\w+([.-]\w+){1,9}"; //other syntactically valid
	if (preg_match("/^".$re."$/i",$str)) return 1;
	if (preg_match("/^".$quoted."$/i",$str)) return 2;
	if (preg_match("/^".$other."$/i",$str)) return 3;
	return 0;
}
function test:
Matches: name.surname@blah.com=1 | "b. blah"@blah.co.nz=2 | a@a.com=1 | a@a.com.au=1 | a@a.au=1 | example@example.com=1 | foo@bar.info=1 | blah@127.0.0.1=1 | e@eee.com=1 | eee@e-e.com=1 | abc@def.gh=1 | a+b_c@d-e_f.gh=1 | abc@def.ghijkl=1 | foo+bar!@example.com=3
Not matches: name surname@blah.com | name."surname"@blah.com | name@bla-.com | .@eee.com | eee@e-.com

Dodaj komentarz