PDA

View Full Version : email validation


ninnypants
04-25-2008, 08:44 PM
I'm writing a registration form that needs email validation on the server side.

function check_email($email){
$reg_x= "^[ _-\.A-Za-z0-9]+@([ _-\.a-z0-9]+\.)+[a-z]{2,3}$";
ereg($reg_x,$email);
}
I include this, and when implemented it throws this error: Warning: ereg() [function.ereg]: REG_ERANGE in C:\xampp\htdocs\smashcards\functions.php on line 4

can anyone help?

kbluhm
04-25-2008, 09:12 PM
Why all these ereg users lately? It's been deprecated in favor of the preg_* library which is a faster alternative that will still be around as of PHP6.

Search Google for php preg_match email for plenty of examples.

Or, if you're using PHP 5.2 or greater, check out filter_var():

function check_email( $email )
{
return ( FALSE !== filter_var( $email, FILTER_VALIDATE_EMAIL ) );
}

tomws
04-25-2008, 09:53 PM
function check_email($email){
$reg_x= "^[ _-\.A-Za-z0-9]+@([ _-\.a-z0-9]+\.)+[a-z]{2,3}$";
ereg($reg_x,$email);
}


If you want to check for a literal dash inside those brackets, make it the last character in the sequence. Right now it's between other characters, so it's being treated as denoting a range (in your case, it's choking on the "range from underscore to backslash").

gsnedders
04-25-2008, 11:06 PM
Also, to add to what kbluhm said, it's actually not that good to use regular expressions for email validation: the formats that are allowed for emails are hugely diverse, and have all kinds of quirks, some of which I'm not sure whether can actually be parsed using regular expressions. Using filter_var() is nice because then it means if it doesn't work it is somebody else's problem. :P

Mwnciau
04-25-2008, 11:44 PM
This (http://fightingforalostcause.net/misc/2006/compare-email-regex.php) is a nice comparison of a few validating regular expressions. The one at the top is pretty much perfect (using the test emails he uses), apart from that it validates emails with non-existant TLDs and domains longer than 64 characters.

/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD

gsnedders
04-26-2008, 02:22 PM
This (http://fightingforalostcause.net/misc/2006/compare-email-regex.php) is a nice comparison of a few validating regular expressions. The one at the top is pretty much perfect (using the test emails he uses), apart from that it validates emails with non-existant TLDs and domains longer than 64 characters.

/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD


To break that: 'foo'(b\(a(lo)r)@'example.com'