11

Possible Duplicate:
How to validate an Email in PHP?

Does PHP have a built in function for determining if an email address is formatted properly. I know it can't go out and check if the email is actually active; I'm talking about just confirming that an email address is structurally correct.

Community
  • 1
  • 1
Ralph M. Rivera
  • 769
  • 3
  • 12
  • 25

1 Answers1

39

filter_var can do this:

$result = filter_var( 'bob@example.com', FILTER_VALIDATE_EMAIL );

It returns false when it failed validation, and returns the e-mail address otherwise.

Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
  • 2
    The validation process in the answer does not check the presence of the dot in addres. `return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);` - tests the presence of a dot in domain name part. email address should be trimmed before the final testing, I think. An integer casting of the return value is also necessary.Found here:electrictoolbox.com/php-email-validation-filter-var-updated. – Istiaque Ahmed Nov 21 '12 at 09:55
  • integer casting is necessary only for echoing purpose. – Istiaque Ahmed Nov 22 '12 at 04:12
  • update 2018: this doesn't work for emails like `Stéphane@yopmail.com`.. – Coder anonymous Dec 26 '18 at 16:50
  • 2
    @Coderanonymous You can add a second flag to make it work for unicode: `filter_var( 'Stéphane@yopmail.com', FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE)` – Ferdinand Frank Apr 14 '21 at 15:03