Asked  6 Months ago    Answers:  5   Viewed   34 times

How can I validate the input value is a valid email address using php5. Now I am using this code

function isValidEmail($email){ 
     $pattern = "^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$"; 

     if (eregi($pattern, $email)){ 
        return true; 
     } 
     else { 
        return false; 
     }    
} 

but it shows deprecated error. How can I fix this issue. Please help me.

 Answers

36

You can use the filter_var() function, which gives you a lot of handy validation and sanitization options.

filter_var($email, FILTER_VALIDATE_EMAIL)
  • PHP Manual filter_var()

  • Available in PHP >= 5.2.0

If you don't want to change your code that relied on your function, just do:

function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Note: For other uses (where you need Regex), the deprecated ereg function family (POSIX Regex Functions) should be replaced by the preg family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.

Update 1: As pointed out by @binaryLV:

PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using strlen() before filter_var(). I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.

This bug has already been fixed.

Update 2: This method will of course validate bazmega@kapa as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: bazmega@kapa.com. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var() with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@.+./', $email);
}

As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.

Tuesday, June 1, 2021
 
Alix
answered 6 Months ago
31

You need to use a delimiter at the beginning and end of your regex, commonly /:

!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$/", trim($_POST['email']))

Manual entry: PCRE introduction / delimiters

Saturday, May 29, 2021
 
Optimus
answered 7 Months ago
19

Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)

function validateEmail(email) {
    const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

Here's the example of regular expresion that accepts unicode:

const re = /^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([^<>()[].,;:s@"]+.)+[^<>()[].,;:s@"]{2,})$/i;

But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.

Here's an example of the above in action:

function validateEmail(email) {
  const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

function validate() {
  const $result = $("#result");
  const email = $("#email").val();
  $result.text("");

  if (validateEmail(email)) {
    $result.text(email + " is valid :)");
    $result.css("color", "green");
  } else {
    $result.text(email + " is not valid :(");
    $result.css("color", "red");
  }
  return false;
}

$("#validate").on("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p>Enter an email address:</p>
  <input id='email'>
  <button type='submit' id='validate'>Validate!</button>
</form>

<h2 id='result'></h2>
Tuesday, June 1, 2021
 
mgraph
answered 6 Months ago
31

Here's a function that I use. It does a little more than just run the email address through a regex, but so far it is the most complete solution that I found:

function validEmail($email, $skipDNS = false)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\.\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\-\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\.\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^(\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/', str_replace("\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\"|[^"])+"$/', str_replace("\\","",$local)))
         {
            $isValid = false;
         }
      }

      if(!$skipDNS)
      {
          if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
          {
             // domain not found in DNS
             $isValid = false;
          }
      }
   }
   return $isValid;
}

The function has an optional $skipDNS argument that can be set to TRUE if you don't want to validate the MX records for the hos. Otherwise the function will attempt to validate that the e-mail address provided actually maps to a real email server.

It's useful to note that most RegEx email validation techniques will validate most e-mail addresses but they will most likely allow some carefully crafted invalid addresses or worst.. fail on some more obscure, but valid e-mail addresses. For more information you may want to check out the Internet Message Formats RFC which describes the allowed format for e-mail addresses.

Friday, August 6, 2021
 
viper
answered 4 Months ago
83

You will need to define a pattern to match against valid e-mails. Patterns are defined using regular expression syntax. Once you have defined a simple type (based on xs:string) with the appropriate pattern, you can use that for your e-mail type.

There are several places on the Internet that provide some examples of such types and patterns. An example of an e-mail type is provided here.

The example given there is as follows (I've edited it slightly to make things a little clearer):

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" > 

  <xsd:element name="A" type="emailAddress"/> 

  <xsd:simpleType name="emailAddress"> 
    <xsd:restriction base="xsd:string"> 
      <xsd:pattern value="[^@]+@[^.]+..+"/> 
    </xsd:restriction> 
  </xsd:simpleType> 
</xsd:schema>
Monday, August 9, 2021
 
nomie
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share