Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

60 lines (45 sloc) 2.601 kb

Validator Chains

Overview

Often multiple validations should be applied to some value in a particular order. The following code demonstrates a way to solve the example from the :ref:`introduction <zend.validator.introduction>`, where a username must be between 6 and 12 alphanumeric characters:

Validators are run in the order they were added to Zend\Validator\ValidatorChain. In the above example, the username is first checked to ensure that its length is between 6 and 12 characters, and then it is checked to ensure that it contains only alphanumeric characters. The second validation, for alphanumeric characters, is performed regardless of whether the first validation, for length between 6 and 12 characters, succeeds. This means that if both validations fail, getMessages() will return failure messages from both validators.

In some cases it makes sense to have a validator break the chain if its validation process fails. Zend\Validator\ValidatorChain supports such use cases with the second parameter to the attach() method. By setting $breakChainOnFailure to TRUE, the added validator will break the chain execution upon failure, which avoids running any other validations that are determined to be unnecessary or inappropriate for the situation. If the above example were written as follows, then the alphanumeric validation would not occur if the string length validation fails:

Any object that implements Zend\Validator\ValidatorInterface may be used in a validator chain.

Jump to Line
Something went wrong with that request. Please try again.