validation.md 9.35 KB
Newer Older
Alexander Makarov committed
1 2 3
Model validation reference
==========================

Larry Ullman committed
4 5 6 7
As a model both represents data and defines the business rules to which that data must adhere, comprehending data validation is key to using Yii. In order to learn model validation basics, please refer to [Model, Validation subsection](model.md#Validation).

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

Alexander Makarov committed
8 9 10 11

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

Larry Ullman committed
12 13 14
The standard Yii validators are defined in many Yii classes, found primarily within the `yii\validators` namespace. But you do not need to specify the full namespace for the standard Yii validators as Yii can recognize them from defined aliases. 

Here's the list of all validators bundled with the Yii framework, including  their most useful properties. The default value for each property is indicated in parentheses. Note that this does not present an exhaustive list of each validator's properties.  
15

16
### `boolean`: [[yii\validators\BooleanValidator|BooleanValidator]]
17 18 19 20 21

Checks if the attribute value is a boolean value.

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

24
### `captcha`: [[yii\captcha\CaptchaValidator|CaptchaValidator]]
25 26

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

Larry Ullman committed
29 30
- `caseSensitive`, whether the comparison is case sensitive. _(false)_
- `captchaAction`, the route of the controller action that renders the CAPTCHA image. _('site/captcha')_
31

32
### `compare`: [[yii\validators\CompareValidator|CompareValidator]]
33 34 35

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

Larry Ullman committed
36 37 38
- `compareAttribute`, the name of the attribute to be compared with. _(currentAttributeName_repeat)_
- `compareValue`, a constant value to be compared with.
- `operator`, the operator for the comparison. _('==')_
39

40
### `date`: [[yii\validators\DateValidator|DateValidator]]
41

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

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

48
### `default`: [[yii\validators\DefaultValueValidator|DefaultValueValidator]]
49 50 51

Sets the attribute to be the specified default value.

Larry Ullman committed
52
- `value`, the default value to be assigned.
53

54
### `double`: [[yii\validators\NumberValidator|NumberValidator]]
55

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

Larry Ullman committed
58 59
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
60

61
### `email`: [[yii\validators\EmailValidator|EmailValidator]]
62

Larry Ullman committed
63
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.
64

Larry Ullman committed
65 66 67 68
- `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)_
69

70
### `exist`: [[yii\validators\ExistValidator|ExistValidator]]
71 72 73

Validates that the attribute value exists in a table.

Larry Ullman committed
74
- `targetClass`, the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
75
  validated. _(ActiveRecord class of the attribute being validated)_
Larry Ullman committed
76
- `targetAttribute`, the ActiveRecord attribute name that should be used to look for the attribute value being validated.
77 78
  _(name of the attribute being validated)_

79
### `file`: [[yii\validators\FileValidator|FileValidator]]
80 81 82

Verifies if an attribute is receiving a valid uploaded file.

Larry Ullman committed
83 84 85 86
- `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)_
87

88
### `filter`: [[yii\validators\FilterValidator|FilterValidator]]
89

Larry Ullman committed
90
Converts the attribute value by sending it through a filter.
91

Larry Ullman committed
92
- `filter`, a PHP callback that defines a filter.
93 94 95 96

Typically a callback is either the name of PHP function:

```php
Alexander Makarov committed
97
['password', 'filter', 'filter' => 'trim'],
98 99 100 101 102
```

Or an anonymous function:

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

109
### `in`: [[yii\validators\RangeValidator|RangeValidator]]
110 111 112

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

Larry Ullman committed
113 114 115
- `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)_
116

117
### `inline`: [[yii\validators\InlineValidator|InlineValidator]]
118

119
Uses a custom function to validate the attribute. You need to define a public method in your
Larry Ullman committed
120 121
model class that 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', 'isDivisibleByTen']`.
122 123

Then, your own method could look like this:
Larry Ullman committed
124

125
```php
Larry Ullman committed
126
public function isDivisibleByTen($attribute) {
127
    if (($this->$attribute % 10) != 0) {
128 129 130 131 132
         $this->addError($attribute, 'cannot divide value by 10');
    }
}
```

133
### `integer`: [[yii\validators\NumberValidator|NumberValidator]]
134

Larry Ullman committed
135
Validates that the attribute value is an integer.
136

Larry Ullman committed
137 138
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
139

140
### `match`: [[yii\validators\RegularExpressionValidator|RegularExpressionValidator]]
141

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

Larry Ullman committed
144 145
- `pattern`, the regular expression to be matched.
- `not`, whether to invert the validation logic. _(false)_
146

147
### `number`: [[yii\validators\NumberValidator|NumberValidator]]
Vincent committed
148 149 150

Validates that the attribute value is a number.

Larry Ullman committed
151 152
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
Vincent committed
153

154
### `required`: [[yii\validators\RequiredValidator|RequiredValidator]]
155

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

Larry Ullman committed
158 159 160
- `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)_
161

162
### `safe`: [[yii\validators\SafeValidator|SafeValidator]]
163 164 165

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

166
### `string`: [[yii\validators\StringValidator|StringValidator]]
167 168 169

Validates that the attribute value is of certain length.

Larry Ullman committed
170 171 172 173
- `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]])_
174

175
### `unique`: [[yii\validators\UniqueValidator|UniqueValidator]]
176 177 178

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

Larry Ullman committed
179
- `targetClass`, the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
180
  validated. _(ActiveRecord class of the attribute being validated)_
Larry Ullman committed
181
- `targetAttribute`, the ActiveRecord attribute name that should be used to look for the attribute value being validated.
182 183
  _(name of the attribute being validated)_

184
### `url`: [[yii\validators\UrlValidator|UrlValidator]]
185 186 187

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

Larry Ullman committed
188 189
- `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
190
  prepended to it. _(null)_
Larry Ullman committed
191
- `enableIDN`, whether the validation process should take into account IDN (internationalized domain names). _(false)_
192 193 194 195

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

Larry Ullman committed
196 197
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:
198 199 200 201

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

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