Programmer's Reference Guide
| Standard Validation Classes |
Validator Chains
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 introduction, where a username must be between 6 and 12 alphanumeric characters:
- // Create a validator chain and add validators to it
- $validatorChain = new Zend_Validate();
- $validatorChain->addValidator(new Zend_Validate_StringLength(6, 12))
- ->addValidator(new Zend_Validate_Alnum());
- // Validate the username
- if ($validatorChain->isValid($username)) {
- // username passed validation
- } else {
- // username failed validation; print reasons
- foreach ($validatorChain->getMessages() as $message) {
- echo "$message\n";
- }
- }
In some cases it makes sense to have a validator break the chain if its validation process fails. Zend_Validate supports such use cases with the second parameter to the addValidator() 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:
- $validatorChain->addValidator(new Zend_Validate_StringLength(6, 12), true)
- ->addValidator(new Zend_Validate_Alnum());
Any object that implements Zend_Validate_Interface may be used in a validator chain.
| Standard Validation Classes |
