27.4. Validating Email Addresses
Prev | Chapter 27. Zend_Validate | Next

## 27.4. Validating Email Addresses

Zend_Validate_Email allows you to validate an email address. The validator first splits the email address on local-part @ hostname and attempts to match these against known specifications for email addresses and hostnames.

Basic usage

A basic example of usage is below:

    <?php
    require_once 'Zend/Validate/EmailAddress.php';
    $validator = new Zend_Validate_EmailAddress();
    if ($validator->isValid($email)) {
        // email appears to be valid
    } else {
        // email is invalid; print the reasons
        foreach ($validator->getMessages() as $message) {
            echo "$message\n";
        }
    }

This will match the email address `$email` and on failure populate `$validator->getMessages()` with useful error messages.

Complex local parts

Zend_Validate_Email will match any valid email address according to RFC2822. For example, valid emails include `bob@domain.com`, `bob+jones@domain.us`, `"bob@jones"@domain.com` and `"bob jones"@domain.com` Some obsolete email formats will not currently validate (i.e. carriage returns or a "\" character in an email address).

Validating different types of hostnames

The hostname part of an email address is validated against Zend_Validate_Hostname. By default only DNS hostnames of the form `domain.com` are accepted, though if you wish you can accept IP addresses and Local hostnames too. To do this you need to instantiate Zend_Validate_EmailAddress passing a parameter to indicate the type of hostnames you want to accept. More details are included in Zend_Validate_Hostname though an example of how to accept both DNS and Local hostnames appears below:

    <?php
    require_once 'Zend/Validate/EmailAddress.php';
    $validator = new Zend_Validate_EmailAddress(Zend_Validate_Hostname::ALLOW_DNS | Zend_Validate_Hostname::ALLOW_LOCAL);
    if ($validator->isValid($email)) {
        // email appears to be valid
    } else {
        // email is invalid; print the reasons
        foreach ($validator->getMessages() as $message) {
            echo "$message\n";
        }
    }

Prev | Up | Next
27.3. Writing Validators | Home | 27.5. Validating Hostnames