input-validation.md 9.39 KB
Newer Older
Alexander Makarov committed
1 2 3
Model validation reference
==========================

Qiang Xue committed
4 5
> Note: This chapter is under development.

Larry Ullman committed
6 7 8 9
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
10 11 12 13

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

Larry Ullman committed
14 15 16
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.  
17

18
### `boolean`: [[yii\validators\BooleanValidator|BooleanValidator]]
19 20 21 22 23

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
24
- `strict`, whether to also compare the type of the value and `trueValue`/`falseValue`. _(false)_
25

26
### `captcha`: [[yii\captcha\CaptchaValidator|CaptchaValidator]]
27 28

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

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

34
### `compare`: [[yii\validators\CompareValidator|CompareValidator]]
35 36 37

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

Larry Ullman committed
38 39 40
- `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. _('==')_
41

42
### `date`: [[yii\validators\DateValidator|DateValidator]]
43

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

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

50
### `default`: [[yii\validators\DefaultValueValidator|DefaultValueValidator]]
51 52 53

Sets the attribute to be the specified default value.

Larry Ullman committed
54
- `value`, the default value to be assigned.
55

56
### `double`: [[yii\validators\NumberValidator|NumberValidator]]
57

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

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

63
### `email`: [[yii\validators\EmailValidator|EmailValidator]]
64

Larry Ullman committed
65
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.
66

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

72
### `exist`: [[yii\validators\ExistValidator|ExistValidator]]
73 74 75

Validates that the attribute value exists in a table.

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

81
### `file`: [[yii\validators\FileValidator|FileValidator]]
82 83 84

Verifies if an attribute is receiving a valid uploaded file.

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

90
### `filter`: [[yii\validators\FilterValidator|FilterValidator]]
91

Larry Ullman committed
92
Converts the attribute value by sending it through a filter.
93

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

Typically a callback is either the name of PHP function:

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

Or an anonymous function:

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

111
### `in`: [[yii\validators\RangeValidator|RangeValidator]]
112 113 114

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

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

119
### `inline`: [[yii\validators\InlineValidator|InlineValidator]]
120

121
Uses a custom function to validate the attribute. You need to define a public method in your
Larry Ullman committed
122 123
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']`.
124 125

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

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

135
### `integer`: [[yii\validators\NumberValidator|NumberValidator]]
136

Larry Ullman committed
137
Validates that the attribute value is an integer.
138

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

142
### `match`: [[yii\validators\RegularExpressionValidator|RegularExpressionValidator]]
143

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

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

149
### `number`: [[yii\validators\NumberValidator|NumberValidator]]
Vincent committed
150 151 152

Validates that the attribute value is a number.

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

156
### `required`: [[yii\validators\RequiredValidator|RequiredValidator]]
157

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

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

164
### `safe`: [[yii\validators\SafeValidator|SafeValidator]]
165 166 167

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

168
### `string`: [[yii\validators\StringValidator|StringValidator]]
169 170 171

Validates that the attribute value is of certain length.

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

177
### `unique`: [[yii\validators\UniqueValidator|UniqueValidator]]
178 179 180

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

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

186
### `url`: [[yii\validators\UrlValidator|UrlValidator]]
187 188 189

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

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

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

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

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

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