58.2. Standard Validation Classes

Zend Framework comes with a standard set of validation classes, which are ready for you to use.

58.2.1. Alnum

Returns true if and only if $value contains only alphabetic and digit characters. This validator includes an option to also consider white space characters as valid.

[Note] Note

The alphabetic characters mean characters that makes up words in each language. However, the English alphabet is treated as the alphabetic characters in following languages: Chinese, Japanese, Korean. The language is specified by Zend_Locale.

58.2.2. Alpha

Returns true if and only if $value contains only alphabetic characters. This validator includes an option to also consider white space characters as valid.

58.2.3. Barcode

This validator is instantiated with a barcode type against which you wish to validate a barcode value. It currently supports "UPC-A" (Universal Product Code) and "EAN-13" (European Article Number) barcode types, and the isValid() method returns true if and only if the input successfully validates against the barcode validation algorithm. You should remove all characters other than the digits zero through nine (0-9) from the input value before passing it on to the validator.

58.2.4. Between

Returns true if and only if $value is between the minimum and maximum boundary values. The comparison is inclusive by default ($value may equal a boundary value), though this may be overridden in order to do a strict comparison, where $value must be strictly greater than the minimum and strictly less than the maximum.

58.2.5. Ccnum

Returns true if and only if $value follows the Luhn algorithm (mod-10 checksum) for credit card numbers.

58.2.6. Date

Returns true if $value is a valid date of the format YYYY-MM-DD. If the optional locale option is set then the date will be validated according to the set locale. And if the optional format option is set this format is used for the validation. For details about the optional parameters see Zend_Date::isDate().

58.2.7. Db_RecordExists and Db_NoRecordExists

Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists provide a means to test whether a record exists in a given table of a database, with a given value.

58.2.7.1. Basic usage

An example of basic usage of the validators:

//Check that the email address exists in the database
$validator = new Zend_Validate_Db_RecordExists('users', 'emailaddress');
if ($validator->isValid($emailaddress)) {
    // email address appears to be valid
} else {
    // email address is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

The above will test that a given email address is in the database table. If no record is found containing the value of $emailaddress in the specified column, then an error message is displayed.

//Check that the username is not present in the database
$validator = new Zend_Validate_Db_NoRecordExists('users', 'username');
if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

The above will test that a given username is not in the database table. If a record is found containing the value of $username in the specified column, then an error message is displayed.

58.2.7.2. Excluding records

Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists also provide a means to test the database, excluding a part of the table, either by providing a where clause as a string, or an array with the keys "field" and "value".

When providing an array for the exclude clause, the != operator is used, so you can check the rest of a table for a value before altering a record (for example on a user profile form)

//Check no other users have the username
$user_id   = $user->getId();
$validator = new Zend_Validate_Db_NoRecordExists(
    'users',
    'username',
    array(
        'field' => 'id',
        'value' => $user_id
    )
);

if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

The above example will check the table to ensure no records other than the one where id = $user_id contains the value $username.

You can also provide a string to the exclude clause so you can use an operator other than !=. This can be useful for testing against composite keys.

$post_id   = $post->getId();
$clause    = $db->quoteInto('post_id = ?', $category_id);
$validator = new Zend_Validate_Db_RecordExists(
    'posts_categories',
    'post_id',
    $clause
);

if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

The above example will check the posts_categories table to ensure that a record with the post_id has a value matching $category_id

58.2.7.3. Database Adapters

You can also specify an adapter, as the fourth parameter when instantiating your validator, this will allow you to work with applications using multiple database adapters, or where you have not set a default adapter. As in the example below:

$validator = new Zend_Validate_Db_RecordExists('users', 'id', null, $dbAdapter);

58.2.8. Digits

Returns true if and only if $value only contains digit characters.

58.2.9. EmailAddress

Zend_Validate_EmailAddress 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:

$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_EmailAddress 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 (e.g. 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:

$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";
    }
}

Checking if the hostname actually accepts email

Just because an email address is in the correct format, it doesn't necessarily mean that email address actually exists. To help solve this problem, you can use MX validation to check whether an MX (email) entry exists in the DNS record for the email's hostname. This tells you that the hostname accepts email, but doesn't tell you the exact email address itself is valid.

MX checking is not enabled by default and at this time is only supported by UNIX platforms. To enable MX checking you can pass a second parameter to the Zend_Validate_EmailAddress constructor.

$validator = new Zend_Validate_EmailAddress(Zend_Validate_Hostname::ALLOW_DNS,
                                            true);

Alternatively you can either pass true or false to $validator->setValidateMx() to enable or disable MX validation.

By enabling this setting network functions will be used to check for the presence of an MX record on the hostname of the email address you wish to validate. Please be aware this will likely slow your script down.

Validating International Domains Names

Zend_Validate_EmailAddress will also match international characters that exist in some domains. This is known as International Domain Name (IDN) support. This is enabled by default, though you can disable this by changing the setting via the internal Zend_Validate_Hostname object that exists within Zend_Validate_EmailAddress.

$validator->hostnameValidator->setValidateIdn(false);

More information on the usage of setValidateIdn() appears in the Zend_Validate_Hostname documentation.

Please note IDNs are only validated if you allow DNS hostnames to be validated.

Validating Top Level Domains

By default a hostname will be checked against a list of known TLDs. This is enabled by default, though you can disable this by changing the setting via the internal Zend_Validate_Hostname object that exists within Zend_Validate_EmailAddress.

$validator->hostnameValidator->setValidateTld(false);

More information on the usage of setValidateTld() appears in the Zend_Validate_Hostname documentation.

Please note TLDs are only validated if you allow DNS hostnames to be validated.

58.2.10. Float

Returns true if and only if $value is a floating-point value. Since Zend Framework 1.8 this validator takes into account the actual locale from browser, environment or application wide set locale. You can of course use the get/setLocale accessors to change the used locale or give it while creating a instance of this validator.

58.2.11. GreaterThan

Returns true if and only if $value is greater than the minimum boundary.

58.2.12. Hex

Returns true if and only if $value contains only hexadecimal digit characters.

58.2.13. Hostname

Zend_Validate_Hostname allows you to validate a hostname against a set of known specifications. It is possible to check for three different types of hostnames: a DNS Hostname (i.e. domain.com), IP address (i.e. 1.2.3.4), and Local hostnames (i.e. localhost). By default only DNS hostnames are matched.

Basic usage

A basic example of usage is below:

$validator = new Zend_Validate_Hostname();
if ($validator->isValid($hostname)) {
    // hostname appears to be valid
} else {
    // hostname is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

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

Validating different types of hostnames

You may find you also want to match IP addresses, Local hostnames, or a combination of all allowed types. This can be done by passing a parameter to Zend_Validate_Hostname when you instantiate it. The parameter should be an integer which determines what types of hostnames are allowed. You are encouraged to use the Zend_Validate_Hostname constants to do this.

The Zend_Validate_Hostname constants are: ALLOW_DNS to allow only DNS hostnames, ALLOW_IP to allow IP addresses, ALLOW_LOCAL to allow local network names, and ALLOW_ALL to allow all three types. To just check for IP addresses you can use the example below:

$validator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_IP);
if ($validator->isValid($hostname)) {
    // hostname appears to be valid
} else {
    // hostname is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

As well as using ALLOW_ALL to accept all hostnames types you can combine these types to allow for combinations. For example, to accept DNS and Local hostnames instantiate your Zend_Validate_Hostname object as so:

$validator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS |
                                        Zend_Validate_Hostname::ALLOW_IP);

Validating International Domains Names

Some Country Code Top Level Domains (ccTLDs), such as 'de' (Germany), support international characters in domain names. These are known as International Domain Names (IDN). These domains can be matched by Zend_Validate_Hostname via extended characters that are used in the validation process.

At present the list of supported ccTLDs include:

  • at (Austria)

  • ch (Switzerland)

  • li (Liechtenstein)

  • de (Germany)

  • fi (Finland)

  • hu (Hungary)

  • no (Norway)

  • se (Sweden)

To match an IDN domain it's as simple as just using the standard Hostname validator since IDN matching is enabled by default. If you wish to disable IDN validation this can be done by by either passing a parameter to the Zend_Validate_Hostname constructor or via the $validator->setValidateIdn() method.

You can disable IDN validation by passing a second parameter to the Zend_Validate_Hostname constructor in the following way.

$validator =
    new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS, false);

Alternatively you can either pass TRUE or FALSE to $validator->setValidateIdn() to enable or disable IDN validation. If you are trying to match an IDN hostname which isn't currently supported it is likely it will fail validation if it has any international characters in it. Where a ccTLD file doesn't exist in Zend/Validate/Hostname specifying the additional characters a normal hostname validation is performed.

Please note IDNs are only validated if you allow DNS hostnames to be validated.

Validating Top Level Domains

By default a hostname will be checked against a list of known TLDs. If this functionality is not required it can be disabled in much the same way as disabling IDN support. You can disable TLD validation by passing a third parameter to the Zend_Validate_Hostname constructor. In the example below we are supporting IDN validation via the second parameter.

$validator =
    new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS,
                               true,
                               false);

Alternatively you can either pass TRUE or FALSE to $validator->setValidateTld() to enable or disable TLD validation.

Please note TLDs are only validated if you allow DNS hostnames to be validated.

58.2.14. Iban

Returns true if and only if $value contains a valid IBAN (International Bank Account Number). IBAN numbers are validated against the country where they are used and by a checksum.

There are two ways to validate IBAN numbers. As first way you can give a locale which represents a country. Any given IBAN number will then be validated against this country.

$validator = new Zend_Validate_Iban('de_AT');
$iban = 'AT611904300234573201';
if ($validator->isValid($iban)) {
    // IBAN appears to be valid
} else {
    // IBAN is invalid
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

This should be done when you want to validate IBAN numbers for a single countries. The simpler way of validation is not to give a locale like shown in the next example.

$validator = new Zend_Validate_Iban();
$iban = 'AT611904300234573201';
if ($validator->isValid($iban)) {
    // IBAN appears to be valid
} else {
    // IBAN is invalid
}

But this shows one big problem: When you have to accept only IBAN numbers from one single country, for example france, then IBAN numbers from other countries would also be valid. Therefor just remember: When you have to validate a IBAN number against a defined country you should give the locale. And when you accept all IBAN numbers regardless of any country omit the locale for simplicity.

58.2.15. InArray

Returns true if and only if a "needle" $value is contained in a "haystack" array. If the strict option is true, then the type of $value is also checked.

58.2.16. Int

Returns true if and only if $value is a valid integer. Since Zend Framework 1.8 this validator takes into account the actual locale from browser, environment or application wide set locale. You can of course use the get/setLocale accessors to change the used locale or give it while creating a instance of this validator.

58.2.17. Ip

Returns true if and only if $value is a valid IP address.

58.2.18. LessThan

Returns true if and only if $value is less than the maximum boundary.

58.2.19. NotEmpty

Returns true if and only if $value is not an empty value.

58.2.20. Regex

Returns true if and only if $value matches against a regular expression pattern.

58.2.21. Sitemap Validators

The following validators conform to the Sitemap XML protocol.

58.2.21.1. Sitemap_Changefreq

Validates whether a string is valid for using as a 'changefreq' element in a Sitemap XML document. Valid values are: 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', or 'never'.

Returns true if and only if the value is a string and is equal to one of the frequencies specified above.

58.2.21.2. Sitemap_Lastmod

Validates whether a string is valid for using as a 'lastmod' element in a Sitemap XML document. The lastmod element should contain a W3C date string, optionally discarding information about time.

Returns true if and only if the given value is a string and is valid according to the protocol.

Example 58.1. Sitemap Lastmod Validator

$validator = new Zend_Validate_Sitemap_Lastmod();

$validator->isValid('1999-11-11T22:23:52-02:00'); // true
$validator->isValid('2008-05-12T00:42:52+02:00'); // true
$validator->isValid('1999-11-11'); // true
$validator->isValid('2008-05-12'); // true

$validator->isValid('1999-11-11t22:23:52-02:00'); // false
$validator->isValid('2008-05-12T00:42:60+02:00'); // false
$validator->isValid('1999-13-11'); // false
$validator->isValid('2008-05-32'); // false
$validator->isValid('yesterday'); // false

58.2.21.3. Sitemap_Loc

Validates whether a string is valid for using as a 'loc' element in a Sitemap XML document. This uses Zend_Form::check() internally. Read more at URI Validation.

58.2.21.4. Sitemap_Priority

Validates whether a value is valid for using as a 'priority' element in a Sitemap XML document. The value should be be a decimal between 0.0 and 1.0. This validator accepts both numeric values and string values.

Example 58.2. Sitemap Priority Validator

$validator = new Zend_Validate_Sitemap_Priority();

$validator->isValid('0.1'); // true
$validator->isValid('0.789'); // true
$validator->isValid(0.8); // true
$validator->isValid(1.0); // true

$validator->isValid('1.1'); // false
$validator->isValid('-0.4'); // false
$validator->isValid(1.00001); // false
$validator->isValid(0xFF); // false
$validator->isValid('foo'); // false

58.2.22. StringLength

Returns true if and only if the string length of $value is at least a minimum and no greater than a maximum (when the max option is not null). The setMin() method throws an exception if the minimum length is set to a value greater than the set maximum length, and the setMax() method throws an exception if the maximum length is set to a value less than than the set minimum length. This class supports UTF-8 and other character encodings, based on the current value of iconv.internal_encoding. If you need a different encoding you can set it with the accessor methods getEncoding and setEncoding.

blog comments powered by Disqus