ultimate validate email function


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function validateEmail($email)
  4. {
  5. $isValid = true;
  6. $atIndex = strrpos($email, "@");
  7. if (is_bool($atIndex) && !$atIndex)
  8. {
  9. $isValid = false;
  10. }
  11. else
  12. {
  13. $domain = substr($email, $atIndex+1);
  14. $local = substr($email, 0, $atIndex);
  15. $localLen = strlen($local);
  16. $domainLen = strlen($domain);
  17. if ($localLen < 1 || $localLen > 64)
  18. {
  19. // local part length exceeded
  20. $isValid = false;
  21. }
  22. else if ($domainLen < 1 || $domainLen > 255)
  23. {
  24. // domain part length exceeded
  25. $isValid = false;
  26. }
  27. else if ($local[0] == '.' || $local[$localLen-1] == '.')
  28. {
  29. // local part starts or ends with '.'
  30. $isValid = false;
  31. }
  32. else if (preg_match('/\\.\\./', $local))
  33. {
  34. // local part has two consecutive dots
  35. $isValid = false;
  36. }
  37. else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
  38. {
  39. // character not valid in domain part
  40. $isValid = false;
  41. }
  42. else if (preg_match('/\\.\\./', $domain))
  43. {
  44. // domain part has two consecutive dots
  45. $isValid = false;
  46. }
  47. else if
  48. (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
  49. str_replace("\\\\","",$local)))
  50. {
  51. // character not valid in local part unless
  52. // local part is quoted
  53. if (!preg_match('/^"(\\\\"|[^"])+"$/',
  54. str_replace("\\\\","",$local)))
  55. {
  56. $isValid = false;
  57. }
  58. }
  59. if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
  60. {
  61. // domain not found in DNS
  62. $isValid = false;
  63. }
  64. }
  65. return $isValid;
  66. }
  67.  
  68. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.