59.2. Standard Validation Classes

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

59.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.

59.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.

59.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.

59.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.

59.2.5. Callback

Zend_Validate_Callback allows you to provide a callback with which to validate a given value.

59.2.5.1. Basic usage

The simplest usecase is to have a single function and use it as a callback. Let's expect we have the following function.

function myMethod($value)
{
    // some validation
    return true;
}

To use it within Zend_Validate_Callback you just have to call it this way:

$valid = new Zend_Validate_Callback('myMethod');
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

59.2.5.2. Usage with closures

PHP 5.3 introduces closures, which are basically self-contained or anonymous functions. PHP considers closures another form of callback, and, as such, may be used with Zend_Validate_Callback. As an example:

$valid = new Zend_Validate_Callback(function($value){
    // some validation
    return true;
});

if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

59.2.5.3. Usage with class-based callbacks

Of course it's also possible to use a class method as callback. Let's expect we have the following class method:

class MyClass
{
    public function myMethod($value)
    {
        // some validation
        return true;
    }
}

The definition of the callback is in this case almost the same. You have just to create an instance of the class before the method and create an array describing the callback:

$object = new MyClass;
$valid = new Zend_Validate_Callback(array($object, 'myMethod'));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

You may also define a static method as a callback. Consider the following class definition and validator usage:

class MyClass
{
    public static function test($value)
    {
        // some validation
        return true;
    }
}

$valid = new Zend_Validate_Callback(array('MyClass, 'test'));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Finally, if you are using PHP 5.3, you may define the magic method __invoke() in your class. If you do so, simply providing an instance of the class as the callback will also work:

class MyClass
{
    public function __invoke($value)
    {
        // some validation
        return true;
    }
}

$object = new MyClass();
$valid = new Zend_Validate_Callback($object);
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

59.2.5.4. Adding options

Zend_Validate_Callback also allows the usage of options which are provided as additional arguments to the callback.

Consider the following class and method definition:

class MyClass
{
    function myMethod($value, $option)
    {
        // some validation
        return true;
    }
}

There are two ways to inform the validator of additional options: pass them in the constructor, or pass them to the setOptions() method.

To pass them to the constructor, you would need to pass an array containing two keys, "callback" and "options":

$valid = new Zend_Validate_Callback(array(
    'callback' => array('MyClass', 'myMethod'), 
    'options'  => $option,
));

if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Otherwise, you may pass them to the validator after instantiation:

$valid = new Zend_Validate_Callback(array('MyClass', 'myMethod'));
$valid->setOptions($option);

if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

When making the call to the callback, the value to be validated will always be passed as the first argument to the callback; all other options will follow it. The amount and type of options which can be used is not limited.

59.2.6. Ccnum

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

59.2.7. 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().

59.2.8. 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.

59.2.8.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(
    array(
        'table' => 'users',
        'field' => '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(
    array(
        'table' => 'users',
        'field' => '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.

59.2.8.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(
    array(
        'table' => 'users',
        'field' => 'username',
        'exclude' => 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(
    array(
        'table'   => 'posts_categories',
        'field'   => 'post_id',
        'exclude' => $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

59.2.8.3. Database Adapters

You can also specify an adapter. 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(
    array(
        'table' => 'users',
        'field' => 'id',
        'adapter' => $dbAdapter
    )
);

59.2.8.4. Database Schemas

You can specify a schema within your database for adapters such as PostgreSQL and DB/2 by simply supplying an array with table and schema keys. As in the example below:

$validator = new Zend_Validate_Db_RecordExists(
    array(
        'table'  => 'users',
        'schema' => 'my',
        'field'  => 'id'
    )
);

59.2.9. Digits

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

59.2.10. 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.

59.2.10.1. 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.

59.2.10.2. Options for validating Email Addresses

Zend_Validate_EmailAddress supports several options which can eighter be set at initiation, by giving an array with the related options, or afterwards, by using setOptions(). The following options are supported:

  • allow: Defines which type of domain names are accepted. This option is used in conjunction with the hostname option to set the hostname validator. For more informations about possible values of this option look at ??? and possible ALLOW* constants. This option defaults to ALLOW_DNS.

  • hostname: Sets the hostname validator with which the domain part of the email address will be validated.

  • mx: Defines if the MX records from the server should be detected. If this option is defined to TRUE then the MX records are used to verify if the server accepts emails. This option defaults to FALSE.

  • deep: Defines if the servers MX records should be verified by a deep check. When this option is set to TRUE then additionally to MX records also the A, A6 and AAAA records are used to verify if the server accepts emails. This option defaults to FALSE.

  • domain: Defines if the domain part should be checked. When this option is set to FALSE, then only the local part of the email address will be checked. In this case the hostname validator will not be called. This option defaults to TRUE.

$validator = new Zend_Validate_EmailAddress();
$validator->setOptions(array('domain' => false));

59.2.10.3. 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).

59.2.10.4. Validating only the local part

If you need Zend_Validate_EmailAddress to check only the local part of an email address, and want to disable validation of the hostname, you can set the domain option to FALSE. This forces Zend_Validate_EmailAddress not to validate the hostname part of the email address.

$validator = new Zend_Validate_EmailAddress();
$validator->setOptions(array('domain' => FALSE));

59.2.10.5. 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";
    }
}

59.2.10.6. 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. To enable MX checking you can pass a second parameter to the Zend_Validate_EmailAddress constructor.

$validator = new Zend_Validate_EmailAddress(
    array(
        'allow' => Zend_Validate_Hostname::ALLOW_DNS,
        'mx'    => true
    )
);
[Note] MX Check under Windows

Within Windows environments MX checking is only available when PHP 5.3 or above is used. Below PHP 5.3 MX checking will not be used even if it's activated within the options.

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.

Sometimes validation for MX records returns false, even if emails are accepted. The reason behind this behaviour is, that servers can accept emails even if they do not provide a MX record. In this case they can provide A, A6 or AAAA records. To allow Zend_Validate_EmailAddress to check also for these other records you need to set deep MX validation. This can be done at initiation by setting the deep option or by using setOptions().

$validator = new Zend_Validate_EmailAddress(
    array(
        'allow' => Zend_Validate_Hostname::ALLOW_DNS,
        'mx'    => true,
        'deep'  => true
    )
);
[Warning] Performance warning

You should be aware that enabling MX check will slow down you script because of the used network functions. Enabling deep check will slow down your script even more as it searches the given server for 3 additional types.

[Note] Disallowed IP addresses

You should note that MX validation is only accepted for external servers. When deep MX validation is enabled, then local IP addresses like 192.168.* or 169.254.* are not accepted.

59.2.10.7. 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->getHostnameValidator()->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.

59.2.10.8. 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->getHostnameValidator()->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.

59.2.10.9. Setting messages

Zend_Validate_EmailAddress makes also use of Zend_Validate_Hostname to check the hostname part of a given email address. As with Zend Framework 1.10 you can simply set messages for Zend_Validate_Hostname from within Zend_Validate_EmailAddress.

$validator = new Zend_Validate_EmailAddress();
$validator->setMessages(array(Zend_Validate_Hostname::UNKNOWN_TLD => 'I don't know the TLD you gave'));

Before Zend Framework 1.10 you had to attach the messages to your own Zend_Validate_Hostname, and then set this validator within Zend_Validate_EmailAddress to get your own messages returned.

59.2.11. 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.

59.2.12. GreaterThan

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

59.2.13. Hex

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

59.2.14. 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.

Until now more than 50 ccTLDs support IDN domains.

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 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(
        array(
            'allow' => Zend_Validate_Hostname::ALLOW_DNS,
            'idn'   => 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(
        array(
            'allow' => Zend_Validate_Hostname::ALLOW_DNS,
            'idn'   => true,
            'tld'   => 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.

59.2.15. 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.

59.2.16. Identical

Returns TRUE if and only if a given token is identical with $value. This validator can handle any given type.

The token to validate against can eighter be set as parameter at initiation, or by using the setToken() method.

// Setting the token at initiation
$validator = new Zend_Validate_Identical(array('one' => 'two'));
if ($validator->isValid(array('one' => 'two'))) { // token valid
    // do something
}

// Setting the token by using setToken()
$validator->setToken(true);
if ($validator->isValid(1)) { // token invalid
    // do something
}

59.2.17. InArray

Zend_Validate_InArray allows you to validate if a given value is contained within an array. It is also able to validate multidimensional arrays.

59.2.17.1. Simple array validation

The simplest way, is just to give the array which should be searched against at initiation:

$validator = new Zend_Validate_InArray(array('key' => 'value',
                                             'otherkey' => 'othervalue'));
if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

This will behave exactly like PHP's in_array() method.

[Note] Note

Per default this validation is not strict nor can it validate multidimensional arrays.

Of course you can give the array to validate against also afterwards by using the setHaystack() method. getHaystack() returns the actual set haystack array.

$validator = new Zend_Validate_InArray();
$validator->setHaystack(array('key' => 'value', 'otherkey' => 'othervalue'));

if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

59.2.17.2. Strict array validation

As mentioned before you can also do a strict validation within the array. Per default there would be no difference between the integer value 0 and the string "0". When doing a strict validation this difference will also be validated and only same types are accepted.

A strict validation can also be done by using two different ways. At initiation and by using a method. At initiation you have to give an array with the following structure:

$validator = new Zend_Validate_InArray(
    array(
        'haystack' => array('key' => 'value', 'otherkey' => 'othervalue'),
        'strict'   => true
    )
);

if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

The haystack key contains your array to validate against. And by setting the strict key to TRUE, the validation is done by using a strict type check.

Of course you can also use the setStrict() method to change this setting afterwards and getStrict() to get the actual set state.

[Note] Note

Note that the strict setting is per default FALSE.

59.2.17.3. Recursive array validation

In addition to PHP's in_array() method this validator can also be used to validate multidimensional arrays.

To validate multidimensional arrays you have to set the recursive option.

$validator = new Zend_Validate_InArray(
    array(
        'haystack' => array(
            'firstDimension' => array('key' => 'value',
                                      'otherkey' => 'othervalue'),
            'secondDimension' => array('some' => 'real',
                                       'different' => 'key')),
        'recursive' => true
    )
);

if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

Your array will then be validated recursive to see if the given value is contained. Additionally you could use setRecursive() to set this option afterwards and getRecursive() to retrieve it.

$validator = new Zend_Validate_InArray(
    array(
        'firstDimension' => array('key' => 'value',
                                  'otherkey' => 'othervalue'),
        'secondDimension' => array('some' => 'real',
                                   'different' => 'key')
    )
);
$validator->setRecursive(true);

if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}
[Note] Default setting for recursion

Per default the recursive validation is turned off.

[Note] Option keys within the haystack

When you are using the keys 'haystack', 'strict' or 'recursive' within your haystack, then you must wrap the haystack key.

59.2.18. 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.

59.2.19. Ip

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

59.2.20. LessThan

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

59.2.21. NotEmpty

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

59.2.22. PostCode

Zend_Validate_PostCode allows you to determine if a given value is a valid postal code. Postal codes are specific to cities, and in some locales termed ZIP codes.

Zend_Validate_PostCode knows more than 160 different postal code formates. To select the correct format there are 2 ways. You can either use a fully qualified locale or you can set your own format manually.

Using a locale is more convenient as Zend Framework already knows the appropriate postal code format for each locale; however, you need to use the fully qualified locale (one containing a region specifier) to do so. For instance, the locale "de" is a locale but could not be used with Zend_Validate_PostCode as it does not include the region; "de_AT", however, would be a valid locale, as it specifies the region code ("AT", for Austria).

$validator = new Zend_Validate_PostCode('de_AT');

When you don't set a locale yourself, then Zend_Validate_PostCode will use the application wide set locale, or, when there is none, the locale returned by Zend_Locale.

// application wide locale within your bootstrap
$locale = new Zend_Locale('de_AT');
Zend_Registry::set('Zend_Locale', $locale);

$validator = new Zend_Validate_PostCode();

You can also change the locale afterwards by calling setLocale(). And of course you can get the actual used locale by calling getLocale().

$validator = new Zend_Validate_PostCode('de_AT');
$validator->setLocale('en_GB');

Postal code formats themself are simply regular expression strings. When the international postal code format, which is used by setting the locale, does not fit your needs, then you can also manually set a format by calling setFormat().

$validator = new Zend_Validate_PostCode('de_AT');
$validator->setFormat('AT-\d{5}');
[Note] Conventions for self defined formats

When using self defined formats you should omit the starting ('/^') and ending tags ('$/'). They are attached automatically.

You should also be aware that postcode values are always be validated in a strict way. This means that they have to be written standalone without additional characters when they are not covered by the format.

59.2.22.1. Constructor options

At it's most basic, you may pass either a Zend_Locale object or a string representing a fully qualified locale to the constructor of Zend_Validate_PostCode.

$validator = new Zend_Validate_PostCode('de_AT');
$validator = new Zend_Validate_PostCode($locale);

Additionally, you may pass either an array or a Zend_Config object to the constructor. When you do so, you must include either the key "locale" or "format"; these will be used to set the appropriate values in the validator object.

$validator = new Zend_Validate_PostCode(array(
    'locale' => 'de_AT',
    'format' => 'AT_\d+'
));

59.2.23. Regex

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

59.2.24. Sitemap Validators

The following validators conform to the Sitemap XML protocol.

59.2.24.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.

59.2.24.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 59.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

59.2.24.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.

59.2.24.4. Sitemap_Priority

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

Example 59.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

59.2.25. 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 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.