|
| 1 | +# Introduction |
| 2 | + |
| 3 | +zend-validator provides a set of commonly needed validators. It also provides a |
| 4 | +simple validator chaining mechanism by which multiple validators may be applied |
| 5 | +to a single datum in a user-defined order. |
| 6 | + |
| 7 | +## What is a validator? |
| 8 | + |
| 9 | +A validator examines its input with respect to some requirements and produces a |
| 10 | +boolean result indicating whether the input successfully validates against the |
| 11 | +requirements. If the input does not meet the requirements, a validator may |
| 12 | +additionally provide information about which requirement(s) the input does not |
| 13 | +meet. |
| 14 | + |
| 15 | +For example, a web application might require that a username be between six and |
| 16 | +twelve characters in length, and may only contain alphanumeric characters. A |
| 17 | +validator can be used for ensuring that a username meets these requirements. If |
| 18 | +a chosen username does not meet one or both of the requirements, it would be |
| 19 | +useful to know which of the requirements the username fails to meet. |
| 20 | + |
| 21 | +## Basic usage of validators |
| 22 | + |
| 23 | +Having defined validation in this way provides the foundation for |
| 24 | +`Zend\Validator\ValidatorInterface`, which defines two methods, `isValid()` and |
| 25 | +`getMessages()`. The `isValid()` method performs validation upon the provided |
| 26 | +value, returning `true` if and only if the value passes against the validation |
| 27 | +criteria. |
| 28 | + |
| 29 | +If `isValid()` returns `false`, the `getMessages()` method will return an array |
| 30 | +of messages explaining the reason(s) for validation failure. The array keys are |
| 31 | +short strings that identify the reasons for validation failure, and the array |
| 32 | +values are the corresponding human-readable string messages. The keys and values |
| 33 | +are class-dependent; each validation class defines its own set of validation |
| 34 | +failure messages and the unique keys that identify them. Each class also has a |
| 35 | +`const` definition that matches each identifier for a validation failure cause. |
| 36 | + |
| 37 | +> ### Stateful validators |
| 38 | +> |
| 39 | +> The `getMessages()` methods return validation failure information only for the |
| 40 | +> most recent `isValid()` call. Each call to `isValid()` clears any messages and |
| 41 | +> errors caused by a previous `isValid()` call, because it's likely that each |
| 42 | +> call to `isValid()` is made for a different input value. |
| 43 | +
|
| 44 | +The following example illustrates validation of an e-mail address: |
| 45 | + |
| 46 | +```php |
| 47 | +use Zend\Validator\EmailAddress; |
| 48 | + |
| 49 | +$validator = new EmailAddress(); |
| 50 | + |
| 51 | +if ($validator->isValid($email)) { |
| 52 | + // email appears to be valid |
| 53 | +} else { |
| 54 | + // email is invalid; print the reasons |
| 55 | + foreach ($validator->getMessages() as $messageId => $message) { |
| 56 | + printf("Validation failure '%s': %s\n", $messageId, $message); |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +## Customizing messages |
| 62 | + |
| 63 | +Validator classes provide a `setMessage()` method with which you can specify the |
| 64 | +format of a message returned by `getMessages()` in case of validation failure. |
| 65 | +The first argument of this method is a string containing the error message. You |
| 66 | +can include tokens in this string which will be substituted with data relevant |
| 67 | +to the validator. The token `%value%` is supported by all validators; this is |
| 68 | +substituted with the value you passed to `isValid()`. Other tokens may be |
| 69 | +supported on a case-by-case basis in each validation class. For example, `%max%` |
| 70 | +is a token supported by `Zend\Validator\LessThan`. The `getMessageVariables()` |
| 71 | +method returns an array of variable tokens supported by the validator. |
| 72 | + |
| 73 | +The second optional argument is a string that identifies the validation failure |
| 74 | +message template to be set, which is useful when a validation class defines more |
| 75 | +than one cause for failure. If you omit the second argument, `setMessage()` |
| 76 | +assumes the message you specify should be used for the first message template |
| 77 | +declared in the validation class. Many validation classes only have one error |
| 78 | +message template defined, so there is no need to specify which message template |
| 79 | +you are changing. |
| 80 | + |
| 81 | +```php |
| 82 | +use Zend\Validator\StringLength; |
| 83 | + |
| 84 | +$validator = new StringLength(8); |
| 85 | + |
| 86 | +$validator->setMessage( |
| 87 | + 'The string \'%value%\' is too short; it must be at least %min% characters', |
| 88 | + StringLength::TOO_SHORT |
| 89 | +); |
| 90 | + |
| 91 | +if (! $validator->isValid('word')) { |
| 92 | + $messages = $validator->getMessages(); |
| 93 | + echo current($messages); |
| 94 | + |
| 95 | + // "The string 'word' is too short; it must be at least 8 characters" |
| 96 | +} |
| 97 | +``` |
| 98 | + |
| 99 | +You can set multiple messages using the `setMessages()` method. Its argument is |
| 100 | +an array containing key/message pairs. |
| 101 | + |
| 102 | +```php |
| 103 | +use Zend\Validator\StringLength; |
| 104 | + |
| 105 | +$validator = new StringLength(['min' => 8, 'max' => 12]); |
| 106 | + |
| 107 | +$validator->setMessages([ |
| 108 | + StringLength::TOO_SHORT => 'The string \'%value%\' is too short', |
| 109 | + StringLength::TOO_LONG => 'The string \'%value%\' is too long', |
| 110 | +]); |
| 111 | +``` |
| 112 | + |
| 113 | +If your application requires even greater flexibility with which it reports |
| 114 | +validation failures, you can access properties by the same name as the message |
| 115 | +tokens supported by a given validation class. The `value` property is always |
| 116 | +available in a validator; it is the value you specified as the argument of |
| 117 | +`isValid()`. Other properties may be supported on a case-by-case basis in each |
| 118 | +validation class. |
| 119 | + |
| 120 | +```php |
| 121 | +use Zend\Validator\StringLength; |
| 122 | + |
| 123 | +$validator = new StringLength(['min' => 8, 'max' => 12]); |
| 124 | + |
| 125 | +if (! $validator->isValid('word')) { |
| 126 | + printf( |
| 127 | + "Word failed: %s; its length is not between %d and %d\n", |
| 128 | + $validator->value, |
| 129 | + $validator->min, |
| 130 | + $validator->max |
| 131 | + ); |
| 132 | +} |
| 133 | +``` |
| 134 | + |
| 135 | +## Translating messages |
| 136 | + |
| 137 | +> ### Translation compatibility |
| 138 | +> |
| 139 | +> In versions 2.0 - 2.1, `Zend\Validator\AbstractValidator` implemented |
| 140 | +> `Zend\I18n\Translator\TranslatorAwareInterface` and accepted instances of |
| 141 | +> `Zend\I18n\Translator\Translator`. Starting in version 2.2.0, zend-validator |
| 142 | +> now defines a translator interface, > `Zend\Validator\Translator\TranslatorInterface`, |
| 143 | +> as well as it's own -aware variant, > `Zend\Validator\Translator\TranslatorAwareInterface`. |
| 144 | +> This was done to reduce dependencies for the component, and follows the |
| 145 | +> principal of Separated Interfaces. |
| 146 | +> |
| 147 | +> The upshot is that if you are migrating from a pre-2.2 version, and receiving |
| 148 | +> errors indicating that the translator provided does not implement |
| 149 | +> `Zend\Validator\Translator\TranslatorInterface`, you will need to make a |
| 150 | +> change to your code. |
| 151 | +> |
| 152 | +> An implementation of `Zend\Validator\Translator\TranslatorInterface` is |
| 153 | +> provided in `Zend\Mvc\I18n\Translator`, which also extends |
| 154 | +> `Zend\I18n\Translator\Translator`. This version can be instantiated and used |
| 155 | +> just as the original `Zend\I18n` version. |
| 156 | +> |
| 157 | +> A new service has also been registered with the MVC, `MvcTranslator`, which |
| 158 | +> will return this specialized, bridge instance. |
| 159 | +> |
| 160 | +> Most users should see no issues, as `Zend\Validator\ValidatorPluginManager` |
| 161 | +> has been modified to use the `MvcTranslator` service internally, which is how |
| 162 | +> most developers were getting the translator instance into validators in the |
| 163 | +> first place. You will only need to change code if you were manually injecting |
| 164 | +> the instance previously. |
| 165 | +
|
| 166 | +Validator classes provide a `setTranslator()` method with which you can specify |
| 167 | +an instance of `Zend\Validator\Translator\TranslatorInterface` which will |
| 168 | +translate the messages in case of a validation failure. The `getTranslator()` |
| 169 | +method returns the translator instance. `Zend\Mvc\I18n\Translator` provides an |
| 170 | +implementation compatible with the validator component. |
| 171 | + |
| 172 | +```php |
| 173 | +use Zend\Mvc\I18n\Translator; |
| 174 | +use Zend\Validator\StringLength; |
| 175 | + |
| 176 | +$validator = new StringLength(['min' => 8, 'max' => 12]); |
| 177 | +$translate = new Translator(); |
| 178 | +// configure the translator... |
| 179 | + |
| 180 | +$validator->setTranslator($translate); |
| 181 | +``` |
| 182 | + |
| 183 | +With the static `AbstractValidator::setDefaultTranslator()` method you can set a |
| 184 | +instance of `Zend\Validator\Translator\TranslatorInterface` which will be used |
| 185 | +for all validation classes, and can be retrieved with `getDefaultTranslator()`. |
| 186 | +This prevents the need for setting a translator manually with each validator. |
| 187 | + |
| 188 | +```php |
| 189 | +use Zend\Mvc\I18n\Translator; |
| 190 | +use Zend\Validator\AbstractValidator; |
| 191 | + |
| 192 | +$translate = new Translator(); |
| 193 | +// configure the translator... |
| 194 | + |
| 195 | +AbstractValidator::setDefaultTranslator($translate); |
| 196 | +``` |
| 197 | + |
| 198 | +Sometimes it is necessary to disable the translator within a validator. To |
| 199 | +achieve this you can use the `setDisableTranslator()` method, which accepts a |
| 200 | +boolean parameter, and `isTranslatorDisabled()` to get the set value. |
| 201 | + |
| 202 | +```php |
| 203 | +use Zend\Validator\StringLength; |
| 204 | + |
| 205 | +$validator = new StringLength(['min' => 8, 'max' => 12]); |
| 206 | +if (! $validator->isTranslatorDisabled()) { |
| 207 | + $validator->setDisableTranslator(); |
| 208 | +} |
| 209 | +``` |
| 210 | + |
| 211 | +It is also possible to use a translator instead of setting own messages with |
| 212 | +`setMessage()`. But doing so, you should keep in mind, that the translator works |
| 213 | +also on messages you set your own. |
0 commit comments