TigerZF
🌐English

Chapter 76. Zend_Validate

Table of Contents

76.1. Introduction
76.1.1. What is a validator?
76.1.2. Basic usage of validators
76.1.3. Customizing messages
76.1.4. Using the static is() method
76.1.4.1. Namespaces
76.1.5. Translating messages
76.2. Standard Validation Classes
76.2.1. Alnum
76.2.1.1. Supported options for Zend_Validate_Alnum
76.2.1.2. Basic usage
76.2.1.3. Using whitespaces
76.2.1.4. Using different languages
76.2.2. Alpha
76.2.2.1. Supported options for Zend_Validate_Alpha
76.2.2.2. Basic usage
76.2.2.3. Using whitespaces
76.2.2.4. Using different languages
76.2.3. Barcode
76.2.3.1. Supported options for Zend_Validate_Barcode
76.2.3.2. Basic usage
76.2.3.3. Optional checksum
76.2.3.4. Writing custom adapters
76.2.4. Between
76.2.4.1. Supported options for Zend_Validate_Between
76.2.4.2. Default behaviour for Zend_Validate_Between
76.2.4.3. Validation exclusive the border values
76.2.5. Callback
76.2.5.1. Supported options for Zend_Validate_Callback
76.2.5.2. Basic usage
76.2.5.3. Usage with closures
76.2.5.4. Usage with class-based callbacks
76.2.5.5. Adding options
76.2.6. CreditCard
76.2.6.1. Supported options for Zend_Validate_CreditCard
76.2.6.2. Basic usage
76.2.6.3. Accepting defined credit cards
76.2.6.4. Validation by using foreign APIs
76.2.7. Ccnum
76.2.8. Date
76.2.8.1. Supported options for Zend_Validate_Date
76.2.8.2. Default date validation
76.2.8.3. Localized date validation
76.2.8.4. Self defined date validation
76.2.9. Db_RecordExists and Db_NoRecordExists
76.2.9.1. Supported options for Zend_Validate_Db_*
76.2.9.2. Basic usage
76.2.9.3. Excluding records
76.2.9.4. Database Adapters
76.2.9.5. Database Schemas
76.2.10. Digits
76.2.10.1. Supported options for Zend_Validate_Digits
76.2.10.2. Validating digits
76.2.11. EmailAddress
76.2.11.1. Basic usage
76.2.11.2. Options for validating Email Addresses
76.2.11.3. Complex local parts
76.2.11.4. Validating only the local part
76.2.11.5. Validating different types of hostnames
76.2.11.6. Checking if the hostname actually accepts email
76.2.11.7. Validating International Domains Names
76.2.11.8. Validating Top Level Domains
76.2.11.9. Setting messages
76.2.12. Float
76.2.12.1. Supported options for Zend_Validate_Float
76.2.12.2. Simple float validation
76.2.12.3. Localized float validation
76.2.13. GreaterThan
76.2.13.1. Supported options for Zend_Validate_GreaterThan
76.2.13.2. Basic usage
76.2.14. Hex
76.2.14.1. Supported options for Zend_Validate_Hex
76.2.15. Hostname
76.2.15.1. Supported options for Zend_Validate_Hostname
76.2.15.2. Basic usage
76.2.15.3. Validating different types of hostnames
76.2.15.4. Validating International Domains Names
76.2.15.5. Validating Top Level Domains
76.2.16. Iban
76.2.16.1. Supported options for Zend_Validate_Iban
76.2.16.2. IBAN validation
76.2.16.2.1. Application wide locale
76.2.16.2.2. Ungreedy IBAN validation
76.2.16.2.3. Region aware IBAN validation
76.2.17. Identical
76.2.17.1. Supported options for Zend_Validate_Identical
76.2.17.2. Basic usage
76.2.17.3. Identical objects
76.2.17.4. Form elements
76.2.17.5. Strict validation
76.2.17.6. Configuration
76.2.18. InArray
76.2.18.1. Supported options for Zend_Validate_InArray
76.2.18.2. Simple array validation
76.2.18.3. Strict array validation
76.2.18.4. Recursive array validation
76.2.19. Int
76.2.19.1. Supported options for Zend_Validate_Int
76.2.19.2. Simple integer validation
76.2.19.3. Localized integer validation
76.2.20. Ip
76.2.20.1. Supported options for Zend_Validate_Ip
76.2.20.2. Basic usage
76.2.20.3. Validate IPv4 or IPV6 alone
76.2.21. Isbn
76.2.21.1. Supported options for Zend_Validate_Isbn
76.2.21.2. Basic usage
76.2.21.3. Setting an explicit ISBN validation type
76.2.21.4. Specifying a separator restriction
76.2.22. LessThan
76.2.22.1. Supported options for Zend_Validate_LessThan
76.2.22.2. Basic usage
76.2.23. NotEmpty
76.2.23.1. Supported options for Zend_Validate_NotEmpty
76.2.23.2. Default behaviour for Zend_Validate_NotEmpty
76.2.23.3. Changing behaviour for Zend_Validate_NotEmpty
76.2.24. PostCode
76.2.24.1. Constructor options
76.2.24.2. Supported options for Zend_Validate_PostCode
76.2.25. Regex
76.2.25.1. Supported options for Zend_Validate_Regex
76.2.25.2. Validation with Zend_Validate_Regex
76.2.25.3. Pattern handling
76.2.26. Sitemap Validators
76.2.26.1. Sitemap_Changefreq
76.2.26.2. Sitemap_Lastmod
76.2.26.3. Sitemap_Loc
76.2.26.4. Sitemap_Priority
76.2.26.5. Supported options for Zend_Validate_Sitemap_*
76.2.27. StringLength
76.2.27.1. Supported options for Zend_Validate_StringLength
76.2.27.2. Default behaviour for Zend_Validate_StringLength
76.2.27.3. Limiting the maximum allowed length of a string
76.2.27.4. Limiting the minimal required length of a string
76.2.27.5. Limiting a string on both sides
76.2.27.6. Encoding of values
76.3. Validator Chains
76.4. Writing Validators
76.5. Validation Messages
76.5.1. Using pre-translated validation messages
76.5.2. Limit the size of a validation message

76.1. Introduction

The Zend_Validate component provides a set of commonly needed validators. It also provides a simple validator chaining mechanism by which multiple validators may be applied to a single datum in a user-defined order.

76.1.1. What is a validator?

A validator examines its input with respect to some requirements and produces a boolean result - whether the input successfully validates against the requirements. If the input does not meet the requirements, a validator may additionally provide information about which requirement(s) the input does not meet.

For example, a web application might require that a username be between six and twelve characters in length and may only contain alphanumeric characters. A validator can be used for ensuring that usernames meet these requirements. If a chosen username does not meet one or both of the requirements, it would be useful to know which of the requirements the username fails to meet.

76.1.2. Basic usage of validators

Having defined validation in this way provides the foundation for Zend_Validate_Interface, which defines two methods, isValid() and getMessages(). The isValid() method performs validation upon the provided value, returning TRUE if and only if the value passes against the validation criteria.

If isValid() returns FALSE, the getMessages() returns an array of messages explaining the reason(s) for validation failure. The array keys are short strings that identify the reasons for validation failure, and the array values are the corresponding human-readable string messages. The keys and values are class-dependent; each validation class defines its own set of validation failure messages and the unique keys that identify them. Each class also has a const definition that matches each identifier for a validation failure cause.

[Note] Note

The getMessages() methods return validation failure information only for the most recent isValid() call. Each call to isValid() clears any messages and errors caused by a previous isValid() call, because it's likely that each call to isValid() is made for a different input value.

The following example illustrates validation of an e-mail address:

$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 $messageId => $message) {
        echo "Validation failure '$messageId': $message\n";
    }
}

76.1.3. Customizing messages

Validate classes provide a setMessage() method with which you can specify the format of a message returned by getMessages() in case of validation failure. The first argument of this method is a string containing the error message. You can include tokens in this string which will be substituted with data relevant to the validator. The token %value% is supported by all validators; this is substituted with the value you passed to isValid(). Other tokens may be supported on a case-by-case basis in each validation class. For example, %max% is a token supported by Zend_Validate_LessThan. The getMessageVariables() method returns an array of variable tokens supported by the validator.

The second optional argument is a string that identifies the validation failure message template to be set, which is useful when a validation class defines more than one cause for failure. If you omit the second argument, setMessage() assumes the message you specify should be used for the first message template declared in the validation class. Many validation classes only have one error message template defined, so there is no need to specify which message template you are changing.

$validator = new Zend_Validate_StringLength(8);

$validator->setMessage(
    'The string \'%value%\' is too short; it must be at least %min% ' .
    'characters',
    Zend_Validate_StringLength::TOO_SHORT);

if (!$validator->isValid('word')) {
    $messages = $validator->getMessages();
    echo current($messages);

    // "The string 'word' is too short; it must be at least 8 characters"
}

You can set multiple messages using the setMessages() method. Its argument is an array containing key/message pairs.

$validator = new Zend_Validate_StringLength(array('min' => 8, 'max' => 12));

$validator->setMessages( array(
    Zend_Validate_StringLength::TOO_SHORT =>
        'The string \'%value%\' is too short',
    Zend_Validate_StringLength::TOO_LONG  =>
        'The string \'%value%\' is too long'
));

If your application requires even greater flexibility with which it reports validation failures, you can access properties by the same name as the message tokens supported by a given validation class. The value property is always available in a validator; it is the value you specified as the argument of isValid(). Other properties may be supported on a case-by-case basis in each validation class.

$validator = new Zend_Validate_StringLength(array('min' => 8, 'max' => 12));

if (!validator->isValid('word')) {
    echo 'Word failed: '
        . $validator->value
        . '; its length is not between '
        . $validator->min
        . ' and '
        . $validator->max
        . "\n";
}

76.1.4. Using the static is() method

If it's inconvenient to load a given validation class and create an instance of the validator, you can use the static method Zend_Validate::is() as an alternative invocation style. The first argument of this method is a data input value, that you would pass to the isValid() method. The second argument is a string, which corresponds to the basename of the validation class, relative to the Zend_Validate namespace. The is() method automatically loads the class, creates an instance, and applies the isValid() method to the data input.

if (Zend_Validate::is($email, 'EmailAddress')) {
    // Yes, email appears to be valid
}

You can also pass an array of constructor arguments, if they are needed for the validator.

if (Zend_Validate::is($value, 'Between', array('min' => 1, 'max' => 12))) {
    // Yes, $value is between 1 and 12
}

The is() method returns a boolean value, the same as the isValid() method. When using the static is() method, validation failure messages are not available.

The static usage can be convenient for invoking a validator ad hoc, but if you have the need to run a validator for multiple inputs, it's more efficient to use the non-static usage, creating an instance of the validator object and calling its isValid() method.

Also, the Zend_Filter_Input class allows you to instantiate and run multiple filter and validator classes on demand to process sets of input data. See Zend_Filter_Input.

76.1.4.1. Namespaces

When working with self defined validators you can give a fourth parameter to Zend_Validate::is() which is the namespace where your validator can be found.

if (Zend_Validate::is($value, 'MyValidator', array('min' => 1, 'max' => 12),
                      array('FirstNamespace', 'SecondNamespace')) {
    // Yes, $value is ok
}

Zend_Validate allows also to set namespaces as default. This means that you can set them once in your bootstrap and have not to give them again for each call of Zend_Validate::is(). The following code snippet is identical to the above one.

Zend_Validate::setDefaultNamespaces(array('FirstNamespace', 'SecondNamespace'));
if (Zend_Validate::is($value, 'MyValidator', array('min' => 1, 'max' => 12)) {
    // Yes, $value is ok
}

if (Zend_Validate::is($value,
                      'OtherValidator',
                      array('min' => 1, 'max' => 12)) {
    // Yes, $value is ok
}

For your convenience there are following methods which allow the handling of namespaces:

  • Zend_Validate::getDefaultNamespaces(): Returns all set default namespaces as array.

  • Zend_Validate::setDefaultNamespaces(): Sets new default namespaces and overrides any previous set. It accepts either a string for a single namespace of an array for multiple namespaces.

  • Zend_Validate::addDefaultNamespaces(): Adds additional namespaces to already set ones. It accepts either a string for a single namespace of an array for multiple namespaces.

  • Zend_Validate::hasDefaultNamespaces(): Returns TRUE when one or more default namespaces are set, and FALSE when no default namespaces are set.

76.1.5. Translating messages

Validate classes provide a setTranslator() method with which you can specify a instance of Zend_Translate which will translate the messages in case of a validation failure. The getTranslator() method returns the set translator instance.

$validator = new Zend_Validate_StringLength(array('min' => 8, 'max' => 12));
$translate = new Zend_Translate(
    array(
        'adapter' => 'array',
        'content' => array(
            Zend_Validate_StringLength::TOO_SHORT => 'Translated \'%value%\''
        ),
        'locale' => 'en'
    )
);

$validator->setTranslator($translate);

With the static setDefaultTranslator() method you can set a instance of Zend_Translate which will be used for all validation classes, and can be retrieved with getDefaultTranslator(). This prevents you from setting a translator manually for all validator classes, and simplifies your code.

$translate = new Zend_Translate(
    array(
        'adapter' => 'array',
        'content' => array(
            Zend_Validate_StringLength::TOO_SHORT => 'Translated \'%value%\''
        ),
        'locale' => 'en'
    )
);
Zend_Validate::setDefaultTranslator($translate);
[Note] Note

When you have set an application wide locale within your registry, then this locale will be used as default translator.

Sometimes it is necessary to disable the translator within a validator. To archive this you can use the setDisableTranslator() method, which accepts a boolean parameter, and translatorIsDisabled() to get the set value.

$validator = new Zend_Validate_StringLength(array('min' => 8, 'max' => 12));
if (!$validator->isTranslatorDisabled()) {
    $validator->setDisableTranslator();
}

It is also possible to use a translator instead of setting own messages with setMessage(). But doing so, you should keep in mind, that the translator works also on messages you set your own.