Zend_Validate | Zend_Validate Programmer's Reference Guide | Standard Validation Classes

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

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

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

1. $validator = new Zend_Validate_EmailAddress();
3. if ($validator->isValid($email)) {
4. // email appears to be valid
5. } else {
6. // email is invalid; print the reasons
7. foreach ($validator->getMessages() as $messageId => $message) {
8. echo "Validation failure '$messageId': $message\n";
9. }
10. }

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

1. $validator = new Zend_Validate_StringLength(8);
3. $validator->setMessage(
4. 'The string \'%value%\' is too short; it must be at least %min% ' .
5. 'characters',
6. Zend_Validate_StringLength::TOO_SHORT);
8. if (!$validator->isValid('word')) {
9. $messages = $validator->getMessages();
10. echo current ($messages);
12. // "The string 'word' is too short; it must be at least 8 characters"
13. }

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

1. $validator = new Zend_Validate_StringLength( array ('min' => 8, 'max' => 12));
3. $validator->setMessages( array (
4. Zend_Validate_StringLength::TOO_SHORT =>
5. 'The string \'%value%\' is too short',
6. Zend_Validate_StringLength::TOO_LONG =>
7. 'The string \'%value%\' is too long'
8. ));

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.

1. $validator = new Zend_Validate_StringLength( array ('min' => 8, 'max' => 12));
3. if (!validator->isValid('word')) {
4. echo 'Word failed: '
5. . $validator->value
6. . '; its length is not between '
7. . $validator->min
8. . ' and '
9. . $validator->max
10. . "\n";
11. }

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

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

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

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

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.

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

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

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.

1. Zend_Validate::setDefaultNamespaces( array ('FirstNamespace', 'SecondNamespace'));
2. if (Zend_Validate::is($value, 'MyValidator', array ('min' => 1, 'max' => 12)) {
3. // Yes, $value is ok
4. }
6. if (Zend_Validate::is($value,
7. 'OtherValidator',
8. array ('min' => 1, 'max' => 12)) {
9. // Yes, $value is ok
10. }

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.

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

1. $validator = new Zend_Validate_StringLength( array ('min' => 8, 'max' => 12));
2. $translate = new Zend_Translate(
3. array (
4. 'adapter' => 'array',
5. 'content' => array (
6. Zend_Validate_StringLength::TOO_SHORT => 'Translated \'%value%\''
7. ),
8. 'locale' => 'en'
9. )
10. );
12. $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.

1. $translate = new Zend_Translate(
2. array (
3. 'adapter' => 'array',
4. 'content' => array (
5. Zend_Validate_StringLength::TOO_SHORT => 'Translated \'%value%\''
6. ),
7. 'locale' => 'en'
8. )
9. );
10. Zend_Validate::setDefaultTranslator($translate);

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

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

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.

Zend_Validate | Zend_Validate Programmer's Reference Guide | Standard Validation Classes