Posted By

jmiller on 05/27/10


Tagged

email validate address


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrianCoyDesign


Check if an email address is valid


 / Published in: PHP
 

  1. /*
  2. Validate an email address.
  3. Provide email address (raw input)
  4. Returns true if the email address has the email
  5. address format and the domain exists.
  6. */
  7. function validEmail($email)
  8. {
  9. $isValid = true;
  10. $atIndex = strrpos($email, "@");
  11. if (is_bool($atIndex) && !$atIndex) {
  12. $isValid = false;
  13. } else {
  14. $domain = substr($email, $atIndex+1);
  15. $local = substr($email, 0, $atIndex);
  16. $localLen = strlen($local);
  17. $domainLen = strlen($domain);
  18.  
  19. if ($localLen < 1 || $localLen > 64) {
  20. // local part length exceeded
  21. $isValid = false;
  22. } else if ($domainLen < 1 || $domainLen > 255) {
  23. // domain part length exceeded
  24. $isValid = false;
  25. } else if ($local[0] == '.' || $local[$localLen-1] == '.') {
  26. // local part starts or ends with '.'
  27. $isValid = false;
  28. } else if (preg_match('/\\.\\./', $local)) {
  29. // local part has two consecutive dots
  30. $isValid = false;
  31. } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
  32. // character not valid in domain part
  33. $isValid = false;
  34. } else if (preg_match('/\\.\\./', $domain)) {
  35. // domain part has two consecutive dots
  36. $isValid = false;
  37. } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
  38. // character not valid in local part unless
  39. // local part is quoted
  40. if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
  41. $isValid = false;
  42. }
  43. }
  44.  
  45. }
  46. return $isValid;
  47. }

Report this snippet  

You need to login to post a comment.