Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Email Validation in PHP (http://www.go4expert.com/articles/email-validation-php-t1128/)

pradeep 5Aug2006 14:58

Email Validation in PHP
Title says it all but to reemphasize that below PHP code block validate an email address. Its always good to have a client side validation for faster user responses but backend check is also needed for user not having client side scripting on.

Code: PHP

    function emailsyntax_is_valid($email) {
      $to_work_out = explode("@", $email);
      if (!isset($to_work_out[0])) return FALSE;
      if (!isset($to_work_out[1])) return FALSE;
      $pattern_local = '^([0-9a-z]*([-|_]?[0-9a-z]+)*)(([-|_]?)\.([-|_]?)[0-9a-z]*([-|_]?[0-9a-z]+)+)*([-|_]?);
      $pattern_domain = '
^([0-9a-z]+([-]?[0-9a-z]+)*)(([-]?)\.([-]?)[0-9a-z]*([-]?[0-9a-z]+)+)*\.[a-z]{2,4} ;
      $match_local = eregi($pattern_local, $to_work_out[0]);
      $match_domain = eregi($pattern_domain, $to_work_out[1]);
      if ($match_local && $match_domain) {
        return TRUE;
      return FALSE;

Use the function like this :

Code: PHP

if (emailsyntax_is_valid($email)) {
      echo "Ok";
    // OR
    if (!emailsyntax_is_valid($email)) {
      echo "Invaild";

All times are GMT +5.5. The time now is 20:13.