input-validation.md 15.7 KB
Newer Older
Qiang Xue committed
1 2
Validating Input
================
Alexander Makarov committed
3

Qiang Xue committed
4 5 6
In the [Models](structure-models.md#validation) section, we have described how data validation works
in general. In this section, we will mainly focus on describing core validators, how to define your
own validators, and different ways of using validators.
Qiang Xue committed
7

Larry Ullman committed
8

Qiang Xue committed
9
## Error Messages
10

Qiang Xue committed
11
## Core Validators
12

Qiang Xue committed
13
Yii provides a set of commonly used validators, found primarily within the `yii\validators` namespace.
14

Qiang Xue committed
15 16
Instead of using lengthy validator class names, you may use *aliases* to specify the use of these core
validators. For example, you can use the alias `required` to refer to the [[yii\validators\RequiredValidator]] class:
17 18 19 20 21

```php
public function rules()
{
    return [
Qiang Xue committed
22
        [['email', 'password'], 'required'],
23 24 25 26
    ];
}
```

Qiang Xue committed
27
The [[yii\validators\Validator::builtInValidators]] property declares all supported validator aliases.
28

Qiang Xue committed
29
In the following, we will describe the main usage and properties of every core validator.
30 31


Qiang Xue committed
32
### [[yii\validators\BooleanValidator|boolean]] <a name="boolean"></a>
33

Qiang Xue committed
34
This validator checks if the input value is a boolean.
35

Qiang Xue committed
36 37 38
- `trueValue`: the value representing *true*. Defaults to `'1'`.
- `falseValue`: the value representing *false*. Defaults to `'0'`.
- `strict`: whether the type of the input value should match that of `trueValue` and `falseValue`. Defaults to `false`.
39 40

```php
Qiang Xue committed
41 42 43
[
    // checks if "selected" is either 0 or 1, regardless of data type
    ['selected', 'boolean'],
44

Qiang Xue committed
45 46 47
    // checks if "deleted" is of boolean type, either true or false
    ['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
]
48 49
```

Qiang Xue committed
50 51
> Note: Because data input submitted via HTML forms are all strings, you normally should leave the
  [[yii\validators\BooleanValidator::strict|strict]] property as false.
52 53


Qiang Xue committed
54
### [[yii\captcha\CaptchaValidator|captcha]] <a name="captcha"></a>
55

Qiang Xue committed
56 57
This validator is usually used together with [[yii\captcha\CaptchaAction]] and [[yii\captcha\Captcha]]
to make sure an input is the same as the verification code displayed by [[yii\captcha\Captcha|CAPTCHA]] widget.
58

Qiang Xue committed
59 60 61 62 63 64 65 66 67 68 69
- `caseSensitive`: whether the comparison of the verification code is case sensitive. Defaults to false.
- `captchaAction`: the [route](structure-controllers.md#routes) corresponding to the
  [[yii\captcha\CaptchaAction|CAPTCHA action]] that renders the CAPTCHA image. Defaults to `'site/captcha'`.
- `skipOnEmpty`: whether the validation can be skipped if the input is empty. Defaults to false,
  which means the input is required.
  
```php
[
    ['verificationCode', 'captcha'],
]
```
70 71


Qiang Xue committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
### [[yii\validators\CompareValidator|compare]] <a name="compare"></a>

This validator compares the specified input value with another one and make sure if their relationship
is as specified by the `operator` property.

- `compareAttribute`: the name of the attribute whose value should be compared with. When the validator
  is being used to validate an attribute, the default value of this property would be the name of
  the attribute suffixed with `_repeat`. For example, if the attribute being validated is `password`,
  then this property will default to `password_repeat`.
- `compareValue`: a constant value that the input value should be compared with. When both 
  of this property and `compareAttribute` are specified, this property will take precedence.
- `operator`: the comparison operator. Defaults to `==`, meaning checking if the input value is equal
  to that of `compareAttribute` or `compareValue`. The following operators are supported:
     * `==`: check if two values are equal. The comparison is done is non-strict mode.
     * `===`: check if two values are equal. The comparison is done is strict mode.
     * `!=`: check if two values are NOT equal. The comparison is done is non-strict mode.
     * `!==`: check if two values are NOT equal. The comparison is done is strict mode.
     * `>`: check if value being validated is greater than the value being compared with.
     * `>=`: check if value being validated is greater than or equal to the value being compared with.
     * `<`: check if value being validated is less than the value being compared with.
     * `<=`: check if value being validated is less than or equal to the value being compared with.
  
```php
[
    // validates if the value of "password" attribute equals to that of "password_repeat"
    ['password', 'compare'],
98

Qiang Xue committed
99 100 101 102
    // validates if age is greater than or equal to 30
    ['age', 'compare', 'compareValue' => 30, 'operator' => '>='],
]
```
103 104


Qiang Xue committed
105
### [[yii\validators\DateValidator|date]] <a name="date"></a>
106

Larry Ullman committed
107
Verifies if the attribute represents a date, time, or datetime in a proper format.
108

Larry Ullman committed
109
- `format`, the date format that the value being validated should follow according to
110
  [PHP date_create_from_format](http://www.php.net/manual/en/datetime.createfromformat.php). _('Y-m-d')_
Larry Ullman committed
111
- `timestampAttribute`, the name of the attribute that should receive the parsed result.
112

Qiang Xue committed
113
### [[yii\validators\DefaultValueValidator|default]] <a name="default"></a>
114 115 116

Sets the attribute to be the specified default value.

Larry Ullman committed
117
- `value`, the default value to be assigned.
118

Qiang Xue committed
119
### [[yii\validators\NumberValidator|double]] <a name="double"></a>
120

Larry Ullman committed
121
Validates that the attribute value is a number, integer or decimal.
122

Larry Ullman committed
123 124
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
125

Qiang Xue committed
126
### [[yii\validators\EmailValidator|email]] <a name="email"></a>
127

Larry Ullman committed
128
Validates that the attribute value is a valid email address. By default, this validator checks if the attribute value is a syntactical valid email address, but the validator can be configured to check the address's domain for the address's existence.
129

Larry Ullman committed
130 131 132 133
- `allowName`, whether to allow the name in the email address (e.g. `John Smith <john.smith@example.com>`). _(false)_.
- `checkMX`, whether to check the MX record for the email address. _(false)_
- `checkPort`, whether to check port 25 for the email address. _(false)_
- `enableIDN`, whether the validation process should take into account IDN (internationalized domain names). _(false)_
134

Qiang Xue committed
135
### [[yii\validators\ExistValidator|exist]] <a name="exist"></a>
136 137 138

Validates that the attribute value exists in a table.

Larry Ullman committed
139
- `targetClass`, the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
140
  validated. _(ActiveRecord class of the attribute being validated)_
Larry Ullman committed
141
- `targetAttribute`, the ActiveRecord attribute name that should be used to look for the attribute value being validated.
142 143
  _(name of the attribute being validated)_

Qiang Xue committed
144
### [[yii\validators\FileValidator|file]] <a name="file"></a>
145 146 147

Verifies if an attribute is receiving a valid uploaded file.

Larry Ullman committed
148 149 150 151
- `types`, an array of file name extensions that are allowed to be uploaded. _(any)_
- `minSize`, the minimum number of bytes required for the uploaded file.
- `maxSize`, the maximum number of bytes allowed for the uploaded file.
- `maxFiles`, the maximum number of files that the given attribute can hold. _(1)_
152

Qiang Xue committed
153
### [[yii\validators\FilterValidator|filter]] <a name="filter"></a>
154

Larry Ullman committed
155
Converts the attribute value by sending it through a filter.
156

Larry Ullman committed
157
- `filter`, a PHP callback that defines a filter.
158 159 160 161

Typically a callback is either the name of PHP function:

```php
Alexander Makarov committed
162
['password', 'filter', 'filter' => 'trim'],
163 164 165 166 167
```

Or an anonymous function:

```php
Alexander Makarov committed
168
['text', 'filter', 'filter' => function ($value) {
169 170
    // here we are removing all swear words from text
    return $newValue;
Alexander Makarov committed
171
}],
172 173
```

Qiang Xue committed
174 175 176
### [[yii\validators\ImageValidator|image]] <a name="image"></a>

### [[yii\validators\RangeValidator|in]] <a name="in"></a>
177 178 179

Validates that the attribute value is among a list of values.

Larry Ullman committed
180 181 182
- `range`, a list of valid values that the attribute value should be among (inclusive).
- `strict`, whether the comparison should be strict (both the type and value must be the same). _(false)_
- `not`, whether to invert the validation logic. _(false)_
183

184

Qiang Xue committed
185
### [[yii\validators\NumberValidator|integer]] <a name="integer"></a>
186

Larry Ullman committed
187
Validates that the attribute value is an integer.
188

Larry Ullman committed
189 190
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
191

Qiang Xue committed
192
### [[yii\validators\RegularExpressionValidator|match]] <a name="match"></a>
193

Larry Ullman committed
194
Validates that the attribute value matches the specified pattern defined by a regular expression.
195

Larry Ullman committed
196 197
- `pattern`, the regular expression to be matched.
- `not`, whether to invert the validation logic. _(false)_
198

Qiang Xue committed
199
### [[yii\validators\NumberValidator|number]] <a name="number"></a>
Vincent committed
200 201 202

Validates that the attribute value is a number.

Larry Ullman committed
203 204
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
Vincent committed
205

Qiang Xue committed
206
### [[yii\validators\RequiredValidator|required]] <a name="required"></a>
207

Larry Ullman committed
208
Validates that the specified attribute does not have a null or empty value.
209

Larry Ullman committed
210 211 212
- `requiredValue`, the desired value that the attribute must have. _(any)_
- `strict`, whether the comparison between the attribute value and
  [[yii\validators\RequiredValidator::requiredValue|requiredValue]] must match both value and type. _(false)_
213

Qiang Xue committed
214
### [[yii\validators\SafeValidator|safe]] <a name="safe"></a>
215 216 217

Serves as a dummy validator whose main purpose is to mark the attributes to be safe for massive assignment.

Qiang Xue committed
218
### [[yii\validators\StringValidator|string]] <a name="string"></a>
219 220 221

Validates that the attribute value is of certain length.

Larry Ullman committed
222 223 224 225
- `length`, specifies the length limit of the value to be validated (inclusive). Can be `exactly X`, `[min X]`, `[min X, max Y]`.
- `max`, the upper length limit (inclusive). If not set, it means no maximum length limit.
- `min`, the lower length limit (inclusive). If not set, it means no minimum length limit.
- `encoding`, the encoding of the string value to be validated. _([[yii\base\Application::charset]])_
226

Qiang Xue committed
227 228 229
### [[yii\validators\FilterValidator|trim]] <a name="trim"></a>

### [[yii\validators\UniqueValidator|unique]] <a name="unique"></a>
230 231 232

Validates that the attribute value is unique in the corresponding database table.

Larry Ullman committed
233
- `targetClass`, the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
234
  validated. _(ActiveRecord class of the attribute being validated)_
Larry Ullman committed
235
- `targetAttribute`, the ActiveRecord attribute name that should be used to look for the attribute value being validated.
236 237
  _(name of the attribute being validated)_

Qiang Xue committed
238
### [[yii\validators\UrlValidator|url]] <a name="url"></a>
239 240 241

Validates that the attribute value is a valid http or https URL.

Larry Ullman committed
242 243
- `validSchemes`, an array of URI schemes that should be considered valid. _['http', 'https']_
- `defaultScheme`, the default URI scheme. If the input doesn't contain the scheme part, the default scheme will be
244
  prepended to it. _(null)_
Larry Ullman committed
245
- `enableIDN`, whether the validation process should take into account IDN (internationalized domain names). _(false)_
246

Qiang Xue committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342

## Creating Validators

If none of the built in validators fit your needs, you can create your own validator by creating a method in you model class.
This method will be wrapped by an [[yii\validators\InlineValidator|InlineValidator]] an be called upon validation.
You will do the validation of the attribute and [[yii\base\Model::addError()|add errors]] to the model when validation fails.

The method has the following signature `public function myValidator($attribute, $params)` while you are free to choose the name.

Here is an example implementation of a validator validating the age of a user:

```php
public function validateAge($attribute, $params)
{
    $value = $this->$attribute;
    if (strtotime($value) > strtotime('now - ' . $params['min'] . ' years')) {
        $this->addError($attribute, 'You must be at least ' . $params['min'] . ' years old to register for this service.');
    }
}

public function rules()
{
    return [
        // ...
        [['birthdate'], 'validateAge', 'params' => ['min' => '12']],
    ];
}
```

You may also set other properties of the [[yii\validators\InlineValidator|InlineValidator]] in the rules definition,
for example the [[yii\validators\InlineValidator::$skipOnEmpty|skipOnEmpty]] property:

```php
[['birthdate'], 'validateAge', 'params' => ['min' => '12'], 'skipOnEmpty' => false],
```


### Inline Validators

### Standalone Validators

## Client-Side Validation

## Conditional Validation


To validate attributes only when certain conditions apply, e.g. the validation of
one field depends on the value of another field you can use [[yii\validators\Validator::when|the `when` property]]
to define such conditions:

```php
['state', 'required', 'when' => function($model) { return $model->country == Country::USA; }],
['stateOthers', 'required', 'when' => function($model) { return $model->country != Country::USA; }],
['mother', 'required', 'when' => function($model) { return $model->age < 18 && $model->married != true; }],
```

For better readability the conditions can also be written like this:

```php
public function rules()
{
    $usa = function($model) { return $model->country == Country::USA; };
    $notUsa = function($model) { return $model->country != Country::USA; };
    $child = function($model) { return $model->age < 18 && $model->married != true; };
    return [
        ['state', 'required', 'when' => $usa],
        ['stateOthers', 'required', 'when' => $notUsa], // note that it is not possible to write !$usa
        ['mother', 'required', 'when' => $child],
    ];
}
```

When you need conditional validation logic on client-side (`enableClientValidation` is true), don't forget
to add `whenClient`:

```php
public function rules()
{
    $usa = [
        'server-side' => function($model) { return $model->country == Country::USA; },
        'client-side' => "function (attribute, value) {return $('#country').value == 'USA';}"
    ];

    return [
        ['state', 'required', 'when' => $usa['server-side'], 'whenClient' => $usa['client-side']],
    ];
}
```

This guide describes all of Yii's validators and their parameters.


## Data Filtering

## Ad Hoc Validation

343

Larry Ullman committed
344 345
Sometimes you need to validate a value that is not bound to any model, such as a standalone email address. The `Validator` class has a
`validateValue` method that can help you in these scenarios. Not all validator classes have implemented this method, but the ones that have implemented `validateValue` can be used without a model. For example, to validate an email stored in a string, you can do the following:
346 347 348 349

```php
$email = 'test@example.com';
$validator = new yii\validators\EmailValidator();
Qiang Xue committed
350
if ($validator->validate($email, $error)) {
351
    echo 'Email is valid.';
352
} else {
353
    echo $error;
354 355
}
```
Alexander Makarov committed
356

Qiang Xue committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
DynamicModel is a model class primarily used to support ad hoc data validation.

The typical usage of DynamicModel is as follows,

```php
public function actionSearch($name, $email)
{
    $model = DynamicModel::validateData(compact('name', 'email'), [
        [['name', 'email'], 'string', 'max' => 128]],
        ['email', 'email'],
    ]);
    if ($model->hasErrors()) {
        // validation fails
    } else {
        // validation succeeds
    }
}
```

The above example shows how to validate `$name` and `$email` with the help of DynamicModel.
The [[validateData()]] method creates an instance of DynamicModel, defines the attributes
using the given data (`name` and `email` in this example), and then calls [[Model::validate()]].

You can check the validation result by [[hasErrors()]], like you do with a normal model.
You may also access the dynamic attributes defined through the model instance, e.g.,
`$model->name` and `$model->email`.

Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:

```php
$model = new DynamicModel(compact('name', 'email'));
$model->addRule(['name', 'email'], 'string', ['max' => 128])
    ->addRule('email', 'email')
    ->validate();
```

DynamicModel implements the above ad-hoc data validation feature by supporting the so-called
"dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor
or [[defineAttribute()]].