views:

144

answers:

3

Possible Duplicate:
What is the best regular expression for validating email addresses?

hello,

can you help with my coding?

my problem is this: when the user wants to register, and when he entered his email. how can i check if it is valid or not?

i use this code.

please help me. tell me if its correct

because i'm only a beginner in php programming.

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

and when i run this code. it does not work. :-(

+6  A: 

If you're on 5.2 or greater, its as easy as

function checkEmail( $email ){
    return filter_var( $email, FILTER_VALIDATE_EMAIL );
}

Which returns the email if it is valid, or FALSE if not.

postpostmodern
This is simple, but it accepts things like `a@bc`. This might not be what he wants.
Mark Byers
Oh wow, I totally didn't realize that. Excuse me while I go update some sites...
postpostmodern
+5  A: 

There are a few errors:

  • You should anchor your regular expression at the start and end of the string.
  • You need to escape the last dot.
  • You should escape the hyphen in the character class or move it to the end.

To fix these errors you would do this:

"/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z]+$/"

There are still a lot of problems as this rejects many valid addresses, including all address like [email protected].

Also there is no need to write:

if (something)
{
    return true;
}
else
{
    return false;
}

Just write:

return something;

I would also advise against using regular expressions to validate emails. Email addressess are very hard to parse correctly using regular expressions. It is better to make some very simple validation that accepts all valid addresses and perhaps some invalid ones, but then send an email to the address and ask the user to click a link to validate the email address. Another advantage of this method is that it doesn't just check that it's a valid email address, but also that it is the correct address.

Mark Byers
+1 but I'd put more emphasis on the last paragraph.
Davy8
+4  A: 
  1. You can simplify it even more by using the method eregi

    function isValidEmail($email){
        return preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
    }
    
  2. Your regular expression doesn't catch all valid email cases.

You can read a little more about regular expressions here : www.regular-expressions.info

gillyb
`eregi` is deprecated, use the preg* functions
Wrikken
I didn't program in php for quite a while, but i just looked it up and realized you are right. I fixed my code accordingly. Thanks.
gillyb
Why are you only allowing 2 or 3 letter TLDs? What about name, museum, info, etc?
Mark Byers