validation.md 7.65 KB
Newer Older
Alexander Makarov committed
1 2 3 4 5 6 7 8 9
Model validation reference
==========================

This guide section doesn't describe how validation works but instead describes all Yii validators and their parameters.
In order to learn model validation basics please refer to [Model, Validation subsection](model.md#Validation).

Standard Yii validators
-----------------------

10
Standard Yii validators could be specified using aliases instead of referring to class names. Here's the list of all
Alexander Mohorev committed
11
validators bundled with Yii with their most useful properties:
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

### `boolean`: [[BooleanValidator]]

Checks if the attribute value is a boolean value.

- `trueValue`, the value representing true status. _(1)_
- `falseValue`, the value representing false status. _(0)_
- `strict`, whether to compare the type of the value and `trueValue`/`falseValue`. _(false)_

### `captcha`: [[CaptchaValidator]]

Validates that the attribute value is the same as the verification code displayed in the CAPTCHA. Should be used together
with [[CaptchaAction]].

- `caseSensitive` whether the comparison is case sensitive. _(false)_
- `captchaAction` the route of the controller action that renders the CAPTCHA image. _('site/captcha')_

### `compare`: [[CompareValidator]]

Compares the specified attribute value with another value and validates if they are equal.

- `compareAttribute` the name of the attribute to be compared with. _(currentAttribute_repeat)_
- `compareValue` the constant value to be compared with.
- `operator` the operator for comparison. _('==')_

### `date`: [[DateValidator]]

Verifies if the attribute represents a date, time or datetime in a proper format.

Qiang Xue committed
41
- `format` the date format that the value being validated should follow according to [[http://www.php.net/manual/en/datetime.createfromformat.php]]. _('Y-m-d')_
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
- `timestampAttribute` the name of the attribute to receive the parsing result.

### `default`: [[DefaultValueValidator]]

Sets the attribute to be the specified default value.

- `value` the default value to be set to the specified attributes.

### `double`: [[NumberValidator]]

Validates that the attribute value is a number.

- `max` limit of the number. _(null)_
- `min` lower limit of the number. _(null)_

### `email`: [[EmailValidator]]

Validates that the attribute value is a valid email address.

- `allowName` whether to allow 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 validation process should take into account IDN (internationalized domain names). _(false)_

### `exist`: [[ExistValidator]]

Validates that the attribute value exists in a table.

70
- `targetClass` the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
71
  validated. _(ActiveRecord class of the attribute being validated)_
72
- `targetAttribute` the ActiveRecord attribute name that should be used to look for the attribute value being validated.
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  _(name of the attribute being validated)_

### `file`: [[FileValidator]]

Verifies if an attribute is receiving a valid uploaded file.

- `types` a list 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 required for the uploaded file.
- `maxFiles` the maximum file count the given attribute can hold. _(1)_

### `filter`: [[FilterValidator]]

Converts the attribute value according to a filter.

- `filter` PHP callback that defines a filter.

Typically a callback is either the name of PHP function:

```php
Alexander Makarov committed
93
['password', 'filter', 'filter' => 'trim'],
94 95 96 97 98
```

Or an anonymous function:

```php
Alexander Makarov committed
99
['text', 'filter', 'filter' => function ($value) {
100 101
	// here we are removing all swear words from text
	return $newValue;
Alexander Makarov committed
102
}],
103 104 105 106 107 108 109 110 111 112
```

### `in`: [[RangeValidator]]

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

- `range` list of valid values that the attribute value should be among.
- `strict` whether the comparison is strict (both type and value must be the same). _(false)_
- `not` whether to invert the validation logic. _(false)_

113 114
### `inline`: [[InlineValidator]]

115 116 117
Uses a custom function to validate the attribute. You need to define a public method in your
model class which will evaluate the validity of the attribute. For example, if an attribute
needs to be divisible by 10. In the rules you would define: `['attributeName', 'myValidationMethod'],`.
118 119 120 121 122 123 124 125 126 127

Then, your own method could look like this:
```php
public function myValidationMethod($attribute) {
    if(($attribute % 10) != 0) {
         $this->addError($attribute, 'cannot divide value by 10');
    }
}
```

128 129 130 131 132 133 134 135 136 137 138 139 140 141
### `integer`: [[NumberValidator]]

Validates that the attribute value is an integer number.

- `max` limit of the number. _(null)_
- `min` lower limit of the number. _(null)_

### `match`: [[RegularExpressionValidator]]

Validates that the attribute value matches the specified pattern defined by regular expression.

- `pattern` the regular expression to be matched with.
- `not` whether to invert the validation logic. _(false)_

Vincent committed
142 143 144 145 146 147 148
### `number`: [[NumberValidator]]

Validates that the attribute value is a number.

- `max` limit of the number. _(null)_
- `min` lower limit of the number. _(null)_

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
### `required`: [[RequiredValidator]]

Validates that the specified attribute does not have null or empty value.

- `requiredValue` the desired value that the attribute must have. _(any)_
- `strict` whether the comparison between the attribute value and [[requiredValue]] is strict. _(false)_

### `safe`: [[SafeValidator]]

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

### `string`: [[StringValidator]]

Validates that the attribute value is of certain length.

Alexander Makarov committed
164
- `length` specifies the length limit of the value to be validated. Can be `exactly X`, `[min X]`, `[min X, max Y]`.
165 166 167 168 169 170 171 172
- `max`  maximum length. If not set, it means no maximum length limit.
- `min` minimum length. If not set, it means no minimum length limit.
- `encoding` the encoding of the string value to be validated. _([[\yii\base\Application::charset]])_

### `unique`: [[UniqueValidator]]

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

173
- `targetClass` the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
174
  validated. _(ActiveRecord class of the attribute being validated)_
175
- `targetAttribute` the ActiveRecord attribute name that should be used to look for the attribute value being validated.
176 177 178 179 180 181
  _(name of the attribute being validated)_

### `url`: [[UrlValidator]]

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

Alexander Makarov committed
182
- `validSchemes` list of URI schemes which should be considered valid. _['http', 'https']_
183 184 185 186 187 188 189 190 191 192 193 194 195 196
- `defaultScheme` the default URI scheme. If the input doesn't contain the scheme part, the default scheme will be
  prepended to it. _(null)_
- `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_

Validating values out of model context
--------------------------------------

Sometimes you need to validate a value that is not bound to any model such as email. In Yii `Validator` class has
`validateValue` method that can help you with it. Not all validator classes have it implemented but the ones that can
operate without model do. In our case to validate an email we can do the following:

```php
$email = 'test@example.com';
$validator = new yii\validators\EmailValidator();
Qiang Xue committed
197
if ($validator->validate($email, $error)) {
198 199
	echo 'Email is valid.';
} else {
Qiang Xue committed
200
	echo $error;
201 202
}
```
Alexander Makarov committed
203

Qiang Xue committed
204
TBD: refer to http://www.yiiframework.com/wiki/56/ for the format