Saltar al contenido

PHP FILTER_VALIDATE_EMAIL no funciona correctamente

Al fin después de tanto trabajar hemos encontrado la respuesta de este enigma que muchos lectores de nuestro sitio web han presentado. Si quieres aportar algo puedes dejar tu conocimiento.

Solución:

Validar direcciones de correo electrónico es algo complicado. Eche un vistazo a esta lista:

Direcciones de correo electrónico válidas

  1. [email protected]
  2. [email protected]
  3. [email protected]
  4. [email protected]
  5. [email protected][IPv6:2001:db8:1ff::a0b:dbd0]
  6. “mucho más inusual” @ example.com
  7. “[email protected]”@ example.com
  8. “muy. (),:; <>[]”.MUY.”[email protected] “muy “. inusual “@ extraño.example.com
  9. [email protected] (los dominios de nivel superior son nombres de host válidos)
  10. [email protected] (nombre de dominio local sin TLD)
  11. ! # $% & ‘* + – / =? ^ _ ` |[email protected]
  12. “() <>[]:,; @ \ “! # $% & ‘* + – / =? ^ _` | ~ .a “@ example.org
  13. “” @ example.org (espacio entre las comillas)
  14. üñîçøðé@example.com (caracteres Unicode en la parte local)

Direcciones de correo electrónico inválidas

  1. Abc.example.com (un carácter @ debe separar las partes local y de dominio)
  2. [email protected]@[email protected] (solo se permite una @ fuera de las comillas)
  3. a “b (c) d, e: f; gi[jk][email protected] (ninguno de los caracteres especiales en esta parte local está permitido fuera de las comillas)
  4. simplemente no”[email protected] (las cadenas entre comillas deben estar separadas por puntos, o el único elemento que forma la parte local)
  5. esto no es[email protected] (los espacios, las comillas y las barras invertidas solo pueden existir cuando están dentro de cadenas entre comillas y están precedidas por una barra invertida)
  6. esto todavía “no [email protected] (incluso si se escapó (precedido por una barra invertida), los espacios, las comillas y las barras invertidas deben incluirse entre comillas)

Fuente http://en.wikipedia.org/wiki/Email_address

Casi todas las implementaciones de validación de correo electrónico tienen “errores”, pero la implementación de php está bien para trabajar porque acepta todas las direcciones de correo electrónico comunes.

ACTUALIZAR:

Encontrado en http://www.php.net/manual/en/filter.filters.validate.php

Respecto a las direcciones “parciales” con núm. en la parte del dominio, un comentario en el código fuente (en ext / filter / logic_filters.c) justifica este rechazo así:

 * The regex below is based on a regex by Michael Rushton.
 * However, it is not identical.  I changed it to only consider routeable
 * addresses as valid.  Michael's regex considers [email protected] a valid address
 * which conflicts with section 2.3.5 of RFC 5321 which states that:
 *
 *   Only resolvable, fully-qualified domain names (FQDNs) are permitted
 *   when domain names are used in SMTP.  In other words, names that can
 *   be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed
 *   in Section 5) are permitted, as are CNAME RRs whose targets can be
 *   resolved, in turn, to MX or address RRs.  Local nicknames or
 *   unqualified names MUST NOT be used.

Y aquí hay un enlace a la clase de Michael Rushton (enlace roto, consulte la fuente a continuación) que admite tanto RFC 5321/5322

[email protected]>
   * @link http://squiloople.com/
   * @package Squiloople
   * @version 1.0
   * @copyright © 2012 Michael Rushton
   */
  /**
   * Email Address Validator
   *
   * Validate email addresses according to the relevant standards
   */
  final class EmailAddressValidator
  integer $standard
     * @return EmailAddressValidator
     */
    public static function setEmailAddress($email_address, $standard = NULL)
    
      return new self($email_address, $standard);
    
    /**
     * Validate the email address using a basic standard
     *
     * @access public
     * @return EmailAddressValidator
     */
    public function setStandardBasic()
    
      // A quoted string local part is not allowed
      $this->_quoted_string = FALSE;
      // An obsolete local part is not allowed
      $this->_obsolete = FALSE;
      // A basic domain name is required
      $this->_basic_domain_name = TRUE;
      // A domain literal domain is not allowed
      $this->_domain_literal = FALSE;
      // Comments and folding white spaces are not allowed
      $this->_cfws = FALSE;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Validate the email address using RFC 5321
     *
     * @access public
     * @return EmailAddressValidator
     */
    public function setStandard5321()
    
      // A quoted string local part is allowed
      $this->_quoted_string = TRUE;
      // An obsolete local part is not allowed
      $this->_obsolete = FALSE;
      // Only a basic domain name is not required
      $this->_basic_domain_name = FALSE;
      // A domain literal domain is allowed
      $this->_domain_literal = TRUE;
      // Comments and folding white spaces are not allowed
      $this->_cfws = FALSE;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Validate the email address using RFC 5322
     *
     * @access public
     * @return EmailAddressValidator
     */
    public function setStandard5322()
    
      // A quoted string local part is disallowed
      $this->_quoted_string = FALSE;
      // An obsolete local part is allowed
      $this->_obsolete = TRUE;
      // Only a basic domain name is not required
      $this->_basic_domain_name = FALSE;
      // A domain literal domain is allowed
      $this->_domain_literal = TRUE;
      // Comments and folding white spaces are allowed
      $this->_cfws = TRUE;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Either allow (true) or do not allow (false) a quoted string local part
     *
     * @access public
     * @param boolean $allow
     * @return EmailAddressValidator
     */
    public function setQuotedString($allow = TRUE)
    
      // Either allow (true) or do not allow (false) a quoted string local part
      $this->_quoted_string = $allow;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Either allow (true) or do not allow (false) an obsolete local part
     *
     * @access public
     * @param boolean $allow
     * @return EmailAddressValidator
     */
    public function setObsolete($allow = TRUE)
    
      // Either allow (true) or do not allow (false) an obsolete local part
      $this->_obsolete = $allow;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Either require (true) or do not require (false) a basic domain name
     *
     * @access public
     * @param boolean $allow
     * @return EmailAddressValidator
     */
    public function setBasicDomainName($allow = TRUE)
    
      // Either require (true) or do not require (false) a basic domain name
      $this->_basic_domain_name = $allow;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Either allow (true) or do not allow (false) a domain literal domain
     *
     * @access public
     * @param boolean $allow
     * @return EmailAddressValidator
     */
    public function setDomainLiteral($allow = TRUE)
    
      // Either allow (true) or do not allow (false) a domain literal domain
      $this->_domain_literal = $allow;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Either allow (true) or do not allow (false) comments and folding white spaces
     *
     * @access public
     * @param boolean $allow
     * @return EmailAddressValidator
     */
    public function setCFWS($allow = TRUE)
    
      // Either allow (true) or do not allow (false) comments and folding white spaces
      $this->_cfws = $allow;
      // Return the EmailAddressValidator object
      return $this;
    
    /**
     * Return the regular expression for a dot atom local part
     *
     * @access private
     * @return string
     */
    private function _getDotAtom()
    
      return "([!#-'*+/-9=?^-~-]+)(?>.(?1))*";
    
    /**
     * Return the regular expression for a quoted string local part
     *
     * @access private
     * @return string
     */
    private function _getQuotedString()
    
      return '"(?>[ !#-[]-~]
    /**
     * Return the regular expression for an obsolete local part
     *
     * @access private
     * @return string
     */
    private function _getObsolete()
    \[x00-xFF]))*'
        . $this->_getFWS()
        . '")(?>'
        . $this->_getCFWS()
        . '.'
        . $this->_getCFWS()
        . '(?1))*';
    
    /**
     * Return the regular expression for a domain name domain
     *
     * @access private
     * @return string
     */
    private function _getDomainName()
    
      // Return the basic domain name format if required
      if ($this->_basic_domain_name)
      
        return '(?>' . $this->_getDomainNameLengthLimit()
          . '[a-zd](?>[a-zd-]*[a-zd])?'
          . $this->_getCFWS()
          . '.'
          . $this->_getCFWS()
          . ')1,126[a-z]2,6';
      
      // Otherwise return the full domain name format
      return $this->_getDomainNameLengthLimit()
        . '([a-zd](?>[a-zd-]*[a-zd])?)(?>'
        . $this->_getCFWS()
        . '.'
        . $this->_getDomainNameLengthLimit()
        . $this->_getCFWS()
        . '(?2))0,126';
    
    /**
     * Return the regular expression for an IPv6 address
     *
     * @access private
     * @return string
     */
    private function _getIPv6()
    (?!(?:.*[a-fd][:]])8,)((?3)(?>:(?3))0,6)?::(?4)?';
    
    /**
     * Return the regular expression for an IPv4-mapped IPv6 address
     *
     * @access private
     * @return string
     */
    private function _getIPv4MappedIPv6()
    (?!(?:.*[a-fd]:)6,)(?5)?::(?>((?3)(?>:(?3))0,4):)?';
    
    /**
     * Return the regular expression for an IPv4 address
     *
     * @access private
     * @return string
     */
    private function _getIPv4()
    1d2
    /**
     * Return the regular expression for a domain literal domain
     *
     * @access private
     * @return string
     */
    private function _getDomainLiteral()
    (?>(?>IPv6:(?>'
        . $this->_getIPv4MappedIPv6()
        . '))?'
        . $this->_getIPv4()
        . '))]';
    
    /**
     * Return either the regular expression for folding white spaces or its backreference
     *
     * @access private
     * @param boolean $define
     * @return string
     */
    private function _getFWS($define = FALSE)
    
      // Return the backreference if $define is set to FALSE otherwise return the regular expression
      if ($this->_cfws)
      (?>[t ]*x0Dx0A)?[t ]+)?)';
      
    
    /**
     * Return the regular expression for comments
     *
     * @access private
     * @return string
     */
    private function _getComments()
    
      return '(?((?>'
        . $this->_getFWS()
        . '(?>[x01-x08x0Bx0Cx0E-'*-[]-x7F]
    /**
     * Return either the regular expression for comments and folding white spaces or its backreference
     *
     * @access private
     * @param boolean $define
     * @return string
     */
    private function _getCFWS($define = FALSE)
    
      // Return the backreference if $define is set to FALSE
      if ($this->_cfws && !$define)
      
        return '(?P>cfws)';
      
      // Otherwise return the regular expression
      if ($this->_cfws)
      '
          . $this->_getFWS()
          . ')?)';
      
    
    /**
     * Establish and return the valid format for the local part
     *
     * @access private
     * @return string
     */
    private function _getLocalPart()
    
      // The local part may be obsolete if allowed
      if ($this->_obsolete)
      
        return $this->_getObsolete();
      
      // Otherwise the local part must be either a dot atom or a quoted string if the latter is allowed
      if ($this->_quoted_string)
      ' . $this->_getQuotedString() . ')';
      
      // Otherwise the local part must be a dot atom
      return $this->_getDotAtom();
    
    /**
     * Establish and return the valid format for the domain
     *
     * @access private
     * @return string
     */
    private function _getDomain()
    
      // The domain must be either a domain name or a domain literal if the latter is allowed
      if ($this->_domain_literal)
      ' . $this->_getDomainLiteral() . ')';
      
      // Otherwise the domain must be a domain name
      return $this->_getDomainName();
    
    /**
     * Return the email address length limit
     *
     * @access private
     * @return string
     */
    private function _getEmailAddressLengthLimit()
    
      return '(?!(?>' . $this->_getCFWS() . '"?(?>\[ -~]
    /**
     * Return the local part length limit
     *
     * @access private
     * @return string
     */
    private function _getLocalPartLengthLimit()
    
      return '(?!(?>' . $this->_getCFWS() . '"?(?>\[ -~]
    /**
     * Establish and return the domain name length limit
     *
     * @access private
     * @return string
     */
    private function _getDomainNameLengthLimit()
    
      return '(?!' . $this->_getCFWS() . '[a-zd-]64,)';
    
    /**
     * Check to see if the domain can be resolved to MX RRs
     *
     * @access private
     * @param array $domain
     * @return integer

Editar 2016: En PHP 7.1 beta, noté lo siguiente:

  • Se implementó la validación de correo electrónico según RFC 6531. (Leo Feyer, Anatol).

Consulte la Sección 3.3 https://tools.ietf.org/html/rfc6531#section-3.3

https://en.wikipedia.org/wiki/International_email

Y algunos buenos ejemplos adicionales

用户@例子.广告                 (Chinese, Unicode)
उपयोगकर्ता@उदाहरण.कॉम           (Hindi, Unicode)
юзер@екзампл.ком             (Ukrainian, Unicode)
θσερ@εχαμπλε.ψομ             (Greek, Unicode)
Dö[email protected]örensen.example.com   (German, Unicode)

FILTER_VALIDATE_EMAIL no es compatible con PHP 5.2.14

Hay una clase PHP en el código de Google para validar direcciones de correo electrónico:

http://code.google.com/p/php-email-address-validation

Puedes usarlo como

include('EmailAddressValidator.php');
$validator = new EmailAddressValidator;
if ($validator->check_email_address('[email protected]'))  
    // Email address is technically valid 
 else 
    // Email not valid

Sección de Reseñas y Valoraciones

No se te olvide dar difusión a este post si te ayudó.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *