EmailValidator

repository·4.x·Indexed 11 days ago

https://github.com/egulias/emailvalidator

A PHP library for validating email addresses against RFC standards (including 5321, 5322, 6530, 6531, 6532, and 1035). It supports multiple validation strategies such as RFCValidation, DNSCheckValidation, SpoofCheckValidation, and MessageIDValidation, which can be combined using MultipleValidationWithAnd. Requires PHP 8.1 or higher.

Tokens
3.4K
Snippets
10
Records
19
Agent score
93%

What's inside EmailValidator

  1. How TLD addresses are handled

    4.x

    Top-Level Domain (TLD) addresses (e.g., an email address where the domain is just the TLD without dots) are permitted by RFC 5321 but are highly unusual.

    Because these are often typos, the library allocates a separate status to these addresses. However, if the library has already established that the domain has a valid MX record, these addresses are treated more leniently.

  2. How DNS validation works

    4.x

    When performing DNS validation, the library attempts to locate an MX record associated with the domain. If a CNAME record is found, the library considers the existence of that CNAME as sufficient evidence that the domain exists.

    For performance reasons, the library does not perform a second DNS lookup for the CNAME's target. Instead, it will raise a warning indicating that an MX record was not immediately found, even though the domain is considered valid via the CNAME.

  3. Understanding TLD format constraints

    4.x
    The library follows constraints regarding TLD formats to avoid ambiguity with IP addresses. Specifically, a valid hostname cannot have the dotted-decimal form #.#.#.# (e.g., 123.123.123.123), as the highest-level component label is not permitted to start with a digit in a way that mimics an IP address.
  4. Extend EmailValidator with custom validation

    4.x
    To implement your own validation logic, create a class that implements the EmailValidation interface. Once implemented, you can pass your custom class instance into the isValid method of the EmailValidator.
  5. Requirements and system dependencies

    4.x

    PHP Version

    • Requires PHP 8.1 or higher.

    System Extensions

    If you use the following validations, your PHP installation must have the PHP Internationalization Libraries (PHP Intl) installed:

    • SpoofCheckValidation
    • DNSCheckValidation

    Tools

  6. Get started with basic RFC validation

    4.x

    To perform standard RFC-compliant email validation, instantiate the EmailValidator class and pass an instance of RFCValidation to the isValid method.

    <?php
    
    use Egulias\
    EmailValidator\\EmailValidator;
    use Egulias\\EmailValidator\\Validation\\RFCValidation;
    
    $validator = new EmailValidator();
    $validator->isValid("example@example.com", new RFCValidation()); // returns true
  7. Use multiple validation strategies with MultipleValidationWithAnd

    4.x

    You can combine multiple validation rules using MultipleValidationWithAnd. This strategy performs a logical AND (&&) operation, meaning the email is only valid if it passes every validation provided in the array.

    <?php
    
    use Egulias\EmailValidator\EmailValidator;
    use Egulias\EmailValidator\Validation\DNSCheckValidation;
    use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
    use Egulias\EmailValidator\Validation\RFCValidation;
    
    $validator = new EmailValidator();
    $multipleValidations = new MultipleValidationWithAnd([
        new RFCValidation(),
        new DNSCheckValidation()
    ]);
    
    // ietf.org has MX records signaling a server with email capabilities
    $validator->isValid("example@ietf.org", $multipleValidations); // returns true
  8. Available validation strategies

    4.x

    EmailValidator provides several built-in validation classes to customize your validation logic:

    • RFCValidation: Standard RFC-like email validation.
    • NoRFCWarningsValidation: RFC-like validation that fails if any warnings (deviations from the RFC that are broadly accepted) are found.
    • DNSCheckValidation: Checks if DNS records exist that signal the server accepts emails (does not guarantee the specific email exists).
    • MultipleValidationWithAnd: Performs a logical AND (&&) over an array of other validations.
    • MessageIDValidation: Validates a field following RFC2822 for message-id.
    • SpoofCheckValidation: (Extra) Checks for multi-UTF-8 characters that might signal an erroneous email name.
  9. Handle multiple validation errors with MultipleErrors

    4.x

    When an email address fails validation for multiple reasons, the MultipleErrors class (which extends InvalidEmail) provides access to all specific failure reasons. You can retrieve the full list of reasons, a single representative reason, or a concatenated string of all error descriptions.

    Key methods:

    • getReasons(): Returns an array of all Reason objects associated with the failure.
    • reason(): Returns a single Reason object. If no reasons are present, it returns an EmptyReason.
    • description(): Returns a string containing the descriptions of all validation errors, separated by newlines.
    // Assuming $result is an instance of MultipleErrors
    if ($result instanceof MultipleErrors) {
        // Get all individual reason objects
        $reasons = $result->getReasons();
    
        // Get a single reason
        $firstReason = $result->reason();
    
        // Get a concatenated string of all error descriptions
        $errorText = $result->description();
    }
  10. Use DNSCheckValidation to verify domain existence

    4.x

    The DNSCheckValidation class performs a DNS lookup to ensure the domain part of an email address has valid DNS records (specifically A, AAAA, or MX records).

    Key Behaviors:

    • Reserved Domains: It automatically rejects domains using reserved TLDs (e.g., .test, .example, .invalid, .localhost) or private namespaces (e.g., .local, .intranet, .lan).
    • Record Requirements: It checks for the presence of DNS_A, DNS_MX, or DNS_AAAA records. If no MX records are found, it falls back to checking A/AAAA records but will issue a NoDNSMXRecord warning.
    • Null MX Support: It respects RFC 7505; if a domain has a "Null MX" record (where the target is empty or .), the email is considered invalid with the reason DomainAcceptsNoMail.
    • Requirements: This class requires the PHP Intl extension to handle IDNA (Internationalized Domain Names in Applications) conversion.
    use Egulias\
    EmailValidator\\
    Validation\\DNSCheckValidation;
    use Egulias\\
    EmailValidator\\
    EmailValidator;
    
    $validator = new EmailValidator();
    $dnsValidation = new DNSCheckValidation();
    
    // The validator will check if the domain in the email has valid DNS records
    $isValid = $dnsValidation->isValid('user@example.com', $emailLexer);
    
    if (!$isValid) {
        $error = $dnsValidation->getError();
        // Handle error (e.g., LocalOrReservedDomain, UnableToGetDNSRecord, etc.)
    }
    
    $warnings = $dnsValidation->getWarnings();