0

Possible Duplicate:
Is there a php library for email address validation?

How can I create a validation for email address?

Community
  • 1
  • 1
sepid
  • 17
  • 1
  • 3

2 Answers2

3

use filter

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}
?>
Alfred
  • 60,935
  • 33
  • 147
  • 186
  • 1
    That's cool! I've never seen that library before. – staticsan Nov 30 '10 at 02:36
  • @staticsan. That might be because you are old-school :)? It is new since PHP5 or something :P. – Alfred Nov 30 '10 at 02:51
  • I find that FILTER_VALIDATE_EMAIL is a little too aggressive in filtering and tends to block some emails that are, technically, valid. That said, I can't remember exactly which emails it was blocking... – El Yobo Nov 30 '10 at 04:43
  • Yah, I got used to pushing the boundaries of PHP4. I'm still finding the boundaries of PHP5. – staticsan Nov 30 '10 at 22:43
2

If you're looking for full control, you can test the email against a regular expression of your own requirements. You can accomplish this using PHP's preg_match() method.

Example:

<?php
   echo preg_match('/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+$/', 'bob@example.com');
?>

If the email address is valid, preg_match will return 1. Otherwise, preg_match will return a value of 0.

-OR- Use PHP's built in filter:

<?php
   echo filter_var('bob@example.com', FILTER_VALIDATE_EMAIL);
?>

Of'course, I've seen many people state that FILTER_VALIDATE_EMAIL is not enough, and return to regular expressions.

You can learn more about PHP regular expressions here: http://php.net/manual/en/book.regex.php

  • The regex you give will restrict valid email addresses, e.g. any of the irish out there like partick.o'malley@example.com; apostrophes (and all sorts of other characters) are actually valid in email address prefixes. – El Yobo Nov 30 '10 at 04:44
  • @El Yobo Yes, surely you can find many regex examples to use for email validation. I've been using this one extensively for the past two to three years and it's been stable. I use a form error rate each week as a Q&A / Analytical statistic to ensure forms are 1). functional, and 2). User-friendly. Best – OV Web Solutions Nov 30 '10 at 21:12