PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Validators

If you subscribe to the security mantra of "filter input, escape output," you'll should use validator to filter input submitted with your form. In Zend_Form, each element includes its own validator chain, consisting of Zend_Validate_* validators.

Validators may be added to the chain in two ways:

  • passing in a concrete validator instance

  • providing a short validator name

Let's see some examples:

<?php
// Concrete validator instance:
$element->addValidator(new Zend_Validate_Alnum());

// Short validator name:
$element->addValidator('Alnum');
$element->addValidator('alnum');

Short names are typically the validator name minus the prefix. In the default case, this will mean minus the 'Zend_Validate_' prefix. As is the case with filters, the first letter can be upper-cased or lower-cased.

Using Custom Validator Classes

If you have your own set of validator classes, you can tell Zend_Form_Element about these using addPrefixPath(). For instance, if you have validators under the 'My_Validator' prefix, you can tell Zend_Form_Element about this as follows:

<?php
$element
->addPrefixPath('My_Validator''My/Validator/''validate');

(Recall that the third argument indicates which plugin loader on which to perform the action.)

If failing a particular validation should prevent later validators from firing, pass boolean TRUE as the second parameter:

<?php
$element
->addValidator('alnum'true);

If you are using a string name to add a validator, and the validator class accepts arguments to the constructor, you may pass these to the third parameter of addValidator() as an array:

<?php
$element
->addValidator('StringLength'false, array(620));

Arguments passed in this way should be in the order in which they are defined in the constructor. The above example will instantiate the Zend_Validate_StringLenth class with its $min and $max parameters:

<?php
$validator 
= new Zend_Validate_StringLength(620);

Providing Custom Validator Error Messages

Some developers may wish to provide custom error messages for a validator. The $options argument of the Zend_Form_Element::addValidator() method allows you to do so by providing the key 'messages' and mapping it to an array of key/value pairs for setting the message templates. You will need to know the error codes of the various validation error types for the particular validator.

A better option is to use a Zend_Translate_Adapter with your form. Error codes are automatically passed to the adapter by the default Errors decorator; you can then specify your own error message strings by setting up translations for the various error codes of your validators.

You can also set many validators at once, using addValidators(). The basic usage is to pass an array of arrays, with each array containing 1 to 3 values, matching the constructor of addValidator():

<?php
$element
->addValidators(array(
    array(
'NotEmpty'true),
    array(
'alnum'),
    array(
'stringLength'false, array(620)),
));

If you want to be more verbose or explicit, you can use the array keys 'validator', 'breakChainOnFailure', and 'options':

<?php
$element
->addValidators(array(
    array(
        
'validator'           => 'NotEmpty',
        
'breakChainOnFailure' => true),
    array(
'validator' => 'alnum'),
    array(
        
'validator' => 'stringLength',
        
'options'   => array(620)),
));

This usage is good for illustrating how you could then configure validators in a config file:

element.validators.notempty.validator = "NotEmpty"
element.validators.notempty.breakChainOnFailure = true
element.validators.alnum.validator = "Alnum"
element.validators.strlen.validator = "StringLength"
element.validators.strlen.options.min = 6
element.validators.strlen.options.max = 20

Notice that every item has a key, whether or not it needs one; this is a limitation of using configuration files -- but it also helps make explicit what the arguments are for. Just remember that any validator options must be specified in order.

To validate an element, pass the value to isValid():

<?php
if ($element->isValid($value)) {
    
// valid
} else {
    
// invalid
}

Validation Operates On Filtered Values

Zend_Form_Element::isValid() filters values through the provided filter chain prior to validation. See the Filters section for more information.

Validation Context

Zend_Form_Element::isValid() supports an additional argument, $context. Zend_Form::isValid() passes the entire array of data being processed to $context when validating a form, and Zend_Form_Element::isValid(), in turn, passes it to each validator. This means you can write validators that are aware of data passed to other form elements. As an example, consider a standard registration form that has fields for both password and a password confirmation; one validation would be that the two fields match. Such a validator might look like the following:

<?php
class My_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
    const 
NOT_MATCH 'notMatch';

    protected 
$_messageTemplates = array(
        
self::NOT_MATCH => 'Password confirmation does not match'
    
);

    public function 
isValid($value$context null)
    {
        
$value = (string) $value;
        
$this->_setValue($value);

        if (
is_array($context)) {
            if (isset(
$context['password_confirm'])
                && (
$value == $context['password_confirm']))
            {
                return 
true;
            }
        } elseif (
is_string($context) && ($value == $context)) {
            return 
true;
        }

        
$this->_error(self::NOT_MATCH);
        return 
false;
    }
}

Validators are processed in order. Each validator is processed, unless a validator created with a TRUE $breakChainOnFailure value fails its validation. Be sure to specify your validators in a reasonable order.

After a failed validation, you can retrieve the error codes and messages from the validator chain:

<?php
$errors   
$element->getErrors();
$messages $element->getMessages();

(Note: error messages returned are an associative array of error code / error message pairs.)

In addition to validators, you can specify that an element is required, using setRequired($flag). By default, this flag is FALSE. In combination with setAllowEmpty($flag) (TRUE by default) and setAutoInsertNotEmptyValidator($flag) (TRUE by default), the behavior of your validator chain can be modified in a number of ways:

  • Using the defaults, validating an Element without passing a value, or passing an empty string for it, skips all validators and validates to TRUE.

  • setAllowEmpty(false) leaving the two other mentioned flags untouched, will validate against the validator chain you defined for this Element, regardless of the value passed to isValid().

  • setRequired(true) leaving the two other mentioned flags untouched, will add a 'NotEmpty' validator on top of the validator chain (if none was already set)), with the $breakChainOnFailure flag set. This behavior lends required flag semantic meaning: if no value is passed, we immediately invalidate the submission and notify the user, and prevent other validators from running on what we already know is invalid data.

    If you do not want this behavior, you can turn it off by passing a FALSE value to setAutoInsertNotEmptyValidator($flag); this will prevent isValid() from placing the 'NotEmpty' validator in the validator chain.

For more information on validators, see the Zend_Validate documentation.

Using Zend_Form_Elements as general-purpose validators

Zend_Form_Element implements Zend_Validate_Interface, meaning an element may also be used as a validator in other, non-form related validation chains.

When is an element detected as empty?

As mentioned the 'NotEmpty' validator is used to detect if an element is empty or not. But Zend_Validate_NotEmpty does, per default, not work like PHP's method empty().

This means when an element contains an integer 0 or an string '0' then the element will be seen as not empty. If you want to have a different behaviour you must create your own instance of Zend_Validate_NotEmpty. There you can define the behaviour of this validator. See Zend_Validate_NotEmpty for details.

Methods associated with validation include:

  • setRequired($flag) and isRequired() allow you to set and retrieve the status of the 'required' flag. When set to boolean TRUE, this flag requires that the element be in the data processed by Zend_Form.

  • setAllowEmpty($flag) and getAllowEmpty() allow you to modify the behaviour of optional elements (i.e., elements where the required flag is FALSE). When the 'allow empty' flag is TRUE, empty values will not be passed to the validator chain.

  • setAutoInsertNotEmptyValidator($flag) allows you to specify whether or not a 'NotEmpty' validator will be prepended to the validator chain when the element is required. By default, this flag is TRUE.

  • addValidator($nameOrValidator, $breakChainOnFailure = false, array $options = null)

  • addValidators(array $validators)

  • setValidators(array $validators) (overwrites all validators)

  • getValidator($name) (retrieve a validator object by name)

  • getValidators() (retrieve all validators)

  • removeValidator($name) (remove validator by name)

  • clearValidators() (remove all validators)

Custom Error Messages

At times, you may want to specify one or more specific error messages to use instead of the error messages generated by the validators attached to your element. Additionally, at times you may want to mark the element invalid yourself. As of 1.6.0, this functionality is possible via the following methods.

  • addErrorMessage($message): add an error message to display on form validation errors. You may call this more than once, and new messages are appended to the stack.

  • addErrorMessages(array $messages): add multiple error messages to display on form validation errors.

  • setErrorMessages(array $messages): add multiple error messages to display on form validation errors, overwriting all previously set error messages.

  • getErrorMessages(): retrieve the list of custom error messages that have been defined.

  • clearErrorMessages(): remove all custom error messages that have been defined.

  • markAsError(): mark the element as having failed validation.

  • hasErrors(): determine whether the element has either failed validation or been marked as invalid.

  • addError($message): add a message to the custom error messages stack and flag the element as invalid.

  • addErrors(array $messages): add several messages to the custom error messages stack and flag the element as invalid.

  • setErrors(array $messages): overwrite the custom error messages stack with the provided messages and flag the element as invalid.

All errors set in this fashion may be translated. Additionally, you may insert the placeholder "%value%" to represent the element value; this current element value will be substituted when the error messages are retrieved.

Zend Framework