Question:
Help with my PHP coding needed!?
Danielle
2012-08-22 19:51:46 UTC
if (!preg_match("/^([a-zA-Z0\-9])+([\.a-zA-Z0-9_\-])*@([a-zA-Z0-9_-
])+(\.[a-zA-Z0-9_\-]+)*\.([a-zA-Z])$/", trim($email == "")))
{
return true;
}
else
{
return false;
}

That is the code that is having the following error:


Warning: preg_match() [function.preg-match]: Compilation failed: range out of order in character class at offset 49 in C:\Inetpub\vhosts\2frame.com.br\httpdocs\envia.php on line 6

I am not very good with PHP syntax, mainly when it comes to the symbol stuff, so could anybody help me fix this code so that the form page's email validation syntax is working properly?
Three answers:
Teoma
2012-08-22 20:14:55 UTC
preg_match('/^[A-Z0-9._%+-]+@(?:[A-Z0-

9-]+\.)+[A-Z]{2,6}$/im', $email);



(Note I have to break the regex into 2 lines because Yahoo crops long lines of code which has also made reading your code impossible)



teoma@website.co..uk // no match

teoma@website.co.uk // match

nobody@fakeweb.mars // match, SEE A PROBLEM?



What is better is to send an email validation to the address using a random string in a database for verification therefore avoiding fake registrations.



Regex is always complicated :)

I use a program called RegexBuddy or look for online regex generators.



Mikes idea is ok but javascript can be manipulated by the user.
Ratchetr
2012-08-23 03:23:55 UTC
Most attempts to validate an email address with a regex are doomed to fail. My best advice is don't bother. Or keep it silly stupid. Look for an @ followed by a . That is as good as you need to get.



Want to see how silly people get trying to regex an email address? See first link.



Wait, it gets worse. See second link.



More fun at the 3'rd link.



And there is always the RFT-822. Happy reading ;-)



I've always thought that trying to validate an email address is a rather pointless exercise (other than the basic sanity checks). Most mistakes are going to come from people mistyping something. Missing a letter, reversing letters, duplicating letters. Basic human typos. A regex won't catch that. I am foo@bar.com. But I'm dyslexic and type 00f@rab.cmo. Can a regex catch that? Nope, that is a perfectly valid email address. Except that it is sure to be bounced, because it isn't a valid email address.



The only real way to validate an email address is to try to send an email to it.



Or you can ask the user to enter it twice. Except I always just copy and paste the first into the second, so if I get the first one wrong, that will fail too.



It's all really not worth the effort, is it?
Mike
2012-08-23 02:59:05 UTC
You are making life more complicated than it needs to be.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...