Commit 01e5ffdc by Qiang Xue

guide WIP [skip ci]

parent 25f919c1
...@@ -173,6 +173,7 @@ Special Topics ...@@ -173,6 +173,7 @@ Special Topics
* [Advanced Application Template](tutorial-advanced-app.md) * [Advanced Application Template](tutorial-advanced-app.md)
* [Building Application from Scratch](tutorial-start-from-scratch.md) * [Building Application from Scratch](tutorial-start-from-scratch.md)
* [Console Commands](tutorial-console.md) * [Console Commands](tutorial-console.md)
* [Core Validators](tutorial-core-validators.md)
* [Internationalization](tutorial-i18n.md) * [Internationalization](tutorial-i18n.md)
* [Mailing](tutorial-mailing.md) * [Mailing](tutorial-mailing.md)
* [Performance Tuning](tutorial-performance-tuning.md) * [Performance Tuning](tutorial-performance-tuning.md)
......
Working with forms Working with Forms
================== ==================
> Note: This section is under development. > Note: This section is under development.
......
Validating Input Validating Input
================ ================
> Note: This section is under development.
In the [Models](structure-models.md#validation) section, we have described how data validation works 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 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. own validators, and different ways of using validators.
## Error Messages ## Declaring Validation Rules
## Core Validators
Yii provides a set of commonly used validators, found primarily within the `yii\validators` namespace.
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:
```php
public function rules()
{
return [
[['email', 'password'], 'required'],
];
}
```
The [[yii\validators\Validator::builtInValidators]] property declares all supported validator aliases.
In the following, we will describe the main usage and properties of every core validator.
### [[yii\validators\BooleanValidator|boolean]] <a name="boolean"></a>
This validator checks if the input value is a boolean.
- `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`.
```php
[
// checks if "selected" is either 0 or 1, regardless of data type
['selected', 'boolean'],
// checks if "deleted" is of boolean type, either true or false
['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
]
```
> Note: Because data input submitted via HTML forms are all strings, you normally should leave the
[[yii\validators\BooleanValidator::strict|strict]] property as false.
### [[yii\captcha\CaptchaValidator|captcha]] <a name="captcha"></a>
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.
- `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'],
]
```
### [[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'],
// validates if age is greater than or equal to 30
['age', 'compare', 'compareValue' => 30, 'operator' => '>='],
]
```
### [[yii\validators\DateValidator|date]] <a name="date"></a>
Verifies if the attribute represents a date, time, or datetime in a proper format.
- `format`, the date format that the value being validated should follow according to
[PHP date_create_from_format](http://www.php.net/manual/en/datetime.createfromformat.php). _('Y-m-d')_
- `timestampAttribute`, the name of the attribute that should receive the parsed result.
### [[yii\validators\DefaultValueValidator|default]] <a name="default"></a>
Sets the attribute to be the specified default value.
- `value`, the default value to be assigned.
### [[yii\validators\NumberValidator|double]] <a name="double"></a>
Validates that the attribute value is a number, integer or decimal.
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
### [[yii\validators\EmailValidator|email]] <a name="email"></a> ## Data Validation
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. ### Getting Error Messages
- `allowName`, whether to allow the name in the email address (e.g. `John Smith <john.smith@example.com>`). _(false)_. ### Empty Values
- `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)_
### [[yii\validators\ExistValidator|exist]] <a name="exist"></a> ### Array Values
Validates that the attribute value exists in a table. ## Data Filtering
- `targetClass`, the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
validated. _(ActiveRecord class of the attribute being validated)_
- `targetAttribute`, the ActiveRecord attribute name that should be used to look for the attribute value being validated.
_(name of the attribute being validated)_
### [[yii\validators\FileValidator|file]] <a name="file"></a>
Verifies if an attribute is receiving a valid uploaded file.
- `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)_
### [[yii\validators\FilterValidator|filter]] <a name="filter"></a>
Converts the attribute value by sending it through a filter.
- `filter`, a PHP callback that defines a filter.
Typically a callback is either the name of PHP function:
```php
['password', 'filter', 'filter' => 'trim'],
```
Or an anonymous function:
```php
['text', 'filter', 'filter' => function ($value) {
// here we are removing all swear words from text
return $newValue;
}],
```
### [[yii\validators\ImageValidator|image]] <a name="image"></a>
### [[yii\validators\RangeValidator|in]] <a name="in"></a>
Validates that the attribute value is among a list of values.
- `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)_
### [[yii\validators\NumberValidator|integer]] <a name="integer"></a>
Validates that the attribute value is an integer.
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
### [[yii\validators\RegularExpressionValidator|match]] <a name="match"></a>
Validates that the attribute value matches the specified pattern defined by a regular expression.
- `pattern`, the regular expression to be matched.
- `not`, whether to invert the validation logic. _(false)_
### [[yii\validators\NumberValidator|number]] <a name="number"></a>
Validates that the attribute value is a number.
- `max`, the upper limit of the number (inclusive). _(null)_
- `min`, the lower limit of the number (inclusive). _(null)_
### [[yii\validators\RequiredValidator|required]] <a name="required"></a>
Validates that the specified attribute does not have a null or empty value.
- `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)_
### [[yii\validators\SafeValidator|safe]] <a name="safe"></a>
Serves as a dummy validator whose main purpose is to mark the attributes to be safe for massive assignment.
### [[yii\validators\StringValidator|string]] <a name="string"></a>
Validates that the attribute value is of certain length.
- `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]])_
### [[yii\validators\FilterValidator|trim]] <a name="trim"></a>
### [[yii\validators\UniqueValidator|unique]] <a name="unique"></a>
Validates that the attribute value is unique in the corresponding database table.
- `targetClass`, the ActiveRecord class name or alias of the class that should be used to look for the attribute value being
validated. _(ActiveRecord class of the attribute being validated)_
- `targetAttribute`, the ActiveRecord attribute name that should be used to look for the attribute value being validated.
_(name of the attribute being validated)_
### [[yii\validators\UrlValidator|url]] <a name="url"></a>
Validates that the attribute value is a valid http or https URL.
- `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
prepended to it. _(null)_
- `enableIDN`, whether the validation process should take into account IDN (internationalized domain names). _(false)_
## Creating Validators ## Creating Validators
...@@ -336,7 +113,7 @@ public function rules() ...@@ -336,7 +113,7 @@ public function rules()
This guide describes all of Yii's validators and their parameters. This guide describes all of Yii's validators and their parameters.
## Data Filtering
## Ad Hoc Validation ## Ad Hoc Validation
......
Core Validators
===============
Yii provides a set of commonly used core validators, found primarily under the `yii\validators` namespace.
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:
```php
public function rules()
{
return [
[['email', 'password'], 'required'],
];
}
```
The [[yii\validators\Validator::builtInValidators]] property declares all supported validator aliases.
In the following, we will describe the main usage and properties of every core validator.
## [[yii\validators\BooleanValidator|boolean]] <a name="boolean"></a>
```php
[
// checks if "selected" is either 0 or 1, regardless of data type
['selected', 'boolean'],
// checks if "deleted" is of boolean type, either true or false
['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
]
```
This validator checks if the input value is a boolean.
- `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`.
> Note: Because data input submitted via HTML forms are all strings, you normally should leave the
[[yii\validators\BooleanValidator::strict|strict]] property as false.
## [[yii\captcha\CaptchaValidator|captcha]] <a name="captcha"></a>
```php
[
['verificationCode', 'captcha'],
]
```
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.
- `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.
## [[yii\validators\CompareValidator|compare]] <a name="compare"></a>
```php
[
// validates if the value of "password" attribute equals to that of "password_repeat"
['password', 'compare'],
// validates if age is greater than or equal to 30
['age', 'compare', 'compareValue' => 30, 'operator' => '>='],
]
```
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.
## [[yii\validators\DateValidator|date]] <a name="date"></a>
```php
[
[['from', 'to'], 'date'],
]
```
This validator checks if the input value is a date, time or datetime in a proper format.
Optionally, it can convert the input value into a UNIX timestamp and store it in an attribute
specified via [[yii\validators\DateValidator::timestampAttribute|timestampAttribute]].
- `format`: the date/time format that the value being validated should be in. Please refer to the
[PHP manual about date_create_from_format()](http://www.php.net/manual/en/datetime.createfromformat.php)
for details about specifying the format string. The default value is `'Y-m-d'`.
- `timestampAttribute`: the name of the attribute to which this validator may assign the UNIX timestamp
converted from the input date/time.
## [[yii\validators\DefaultValueValidator|default]] <a name="default"></a>
```php
[
// set "age" to be null if it is empty
['age', 'default', 'value' => null],
// set "country" to be "USA" if it is empty
['country', 'default', 'value' => 'USA'],
// assign "from" and "to" with a date 3 days and 6 days from today, if they are empty
[['from', 'to'], 'default', 'value' => function ($model, $attribute) {
return date('Y-m-d', strtotime($attribute === 'to' ? '+3 days' : '+6 days'));
}],
]
```
This validator does not validate data. Instead, it assigns a default value to the attributes being validated
if the attributes are empty.
- `value`: the default value or a PHP callable that returns the default value which will be assigned to
the attributes being validated if they are empty. The signature of the PHP callable should be as follows,
```php
function foo($model, $attribute) {
// ... compute $value ...
return $value;
}
```
> Info: How to determine if a value is empty or not is a separate topic covered
in the [Empty Values](input-validation.md#empty-values) section.
## [[yii\validators\NumberValidator|double]] <a name="double"></a>
```php
[
// checks if "salary" is a double number
['salary', 'double'],
]
```
This validator checks if the input value is a double number. It is equivalent to the [number](#number) validator.
- `max`: the upper limit (inclusive) of the value. If not set, it means the validator does not check the upper limit.
- `min`: the lower limit (inclusive) of the value. If not set, it means the validator does not check the lower limit.
## [[yii\validators\EmailValidator|email]] <a name="email"></a>
```php
[
// checks if "email" is a valid email address
['email', 'email'],
]
```
This validator checks if the input value is a valid email address.
- `allowName`: whether to allow name in the email address (e.g. `John Smith <john.smith@example.com>`). Defaults to false.
- `checkDNS`, whether to check whether the email's domain exists and has either an A or MX record.
Be aware that this check may fail due to temporary DNS problems, even if the email address is actually valid.
Defaults to false.
- `enableIDN`, whether the validation process should take into account IDN (internationalized domain names).
Defaults to false. Note that in order to use IDN validation you have to install and enable the `intl` PHP extension,
or an exception would be thrown.
## [[yii\validators\ExistValidator|exist]] <a name="exist"></a>
```php
[
// a1 needs to exist in the column represented by the "a1" attribute
['a1', 'exist'],
// a1 needs to exist, but its value will use a2 to check for the existence
['a1', 'exist', 'targetAttribute' => 'a2'],
// a1 and a2 need to exist together, and they both will receive error message
[['a1', 'a2'], 'exist', 'targetAttribute' => ['a1', 'a2']],
// a1 and a2 need to exist together, only a1 will receive error message
['a1', 'exist', 'targetAttribute' => ['a1', 'a2']],
// a1 needs to exist by checking the existence of both a2 and a3 (using a1 value)
['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']],
// a1 needs to exist. If a1 is an array, then every element of it must exist.
['a1', 'exist', 'allowArray' => true],
]
```
This validator checks if the input value can be found in a table column. It only works
with [Active Record](db-active-record.md) model attributes. It supports validation against
either a single column or multiple columns.
- `targetClass`: the name of the [Active Record](db-active-record.md) class that should be used
to look for the input value being validated. If not set, the class of the model currently being validated will be used.
- `targetAttribute`: the name of the attribute in `targetClass` that should be used to validate the existence
of the input value. If not set, it will use the name of the attribute currently being validated.
You may use an array to validate the existence of multiple columns at the same time. The array values
are the attributes that will be used to validate the existence, while the array keys are the attributes
whose values are to be validated. If the key and the value are the same, you can just specify the value.
- `filter`: additional filter to be applied to the DB query used to check the existence of the input value.
This can be a string or an array representing the additional query condition (refer to [[yii\db\Query::where()]]
on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
is the [[yii\db\Query|Query]] object that you can modify in the function.
- `allowArray`: whether to allow the input value to be an array. Defaults to false. If this property is true
and the input is an array, then every element of the array must exist in the target column. Note that
this property cannot be set true if you are validating against multiple columns by setting `targetAttribute` as an array.
## [[yii\validators\FileValidator|file]] <a name="file"></a>
```php
[
// checks if "primaryImage" is an uploaded image file in PNG, JPG or GIF format.
// the file size must be less than 1MB
['primaryImage', 'file', 'types' => ['png', 'jpg', 'gif'], 'maxSize' => 1024*1024*1024],
]
```
This validator checks if the input is a valid uploaded file.
- `types`: a list of file name extensions that are allowed to be uploaded. This can be either
an array or a string consisting of file extension names separated by space or comma (e.g. "gif, jpg").
Extension names are case-insensitive. Defaults to null, meaning all file name
extensions are allowed.
- `minSize`: the minimum number of bytes required for the uploaded file. Defaults to null, meaning no lower limit.
- `maxSize`: the maximum number of bytes allowed for the uploaded file. Defaults to null, meaning no upper limit.
- `maxFiles`: the maximum number of files that the given attribute can hold. Defaults to 1, meaning
the input must be a single uploaded file. If it is greater than 1, then the input must be an array
consisting of at most `maxFiles` number of uploaded files.
`FileValidator` is used together with [[yii\web\UploadedFile]]. Please refer to the [Uploading Files](input-file-upload.md)
section for complete coverage about uploading files and performing validation about the uploaded files.
## [[yii\validators\FilterValidator|filter]] <a name="filter"></a>
```php
[
// trim "username" and "email" inputs
[['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],
// normalize "phone" input
['phone', 'filter', 'filter' => function ($value) {
// normalize phone input here
return $value;
}],
]
```
This validator does not validate data. Instead, it applies a filter on the input value and assigns it
back to the attribute being validated.
- `filter`: a PHP callback that defines a filter. This can be a global function name, an anonymous function, etc.
The function signature must be `function ($value) { return $newValue; }`. This property must be set.
- `skipOnArray`: whether to skip the filter if the input value is an array. Defaults to false.
Note that if the filter cannot handle array input, you should set this property to be true. Otherwise some
PHP error might occur.
> Tip: If you want to trim input values, you may directly use [trim](#trim) validator.
## [[yii\validators\ImageValidator|image]] <a name="image"></a>
```php
[
// checks if "primaryImage" is a valid image with proper size
['primaryImage', 'image', 'types' => 'png, jpg',
'minWidth' => 100, 'maxWidth' => 1000,
'minHeight' => 100, 'maxHeight' => 1000,
],
]
```
This validator checks if the input value represents a valid image file. It extends from the [file](#file) validator
and thus inherits all its properties. Besides, it supports the following additional properties specific for image
validation purpose:
- `minWidth`: the minimum width of the image. Defaults to null, meaning no lower limit.
- `maxWidth`: the maximum width of the image. Defaults to null, meaning no upper limit.
- `minHeight`: the minimum height of the image. Defaults to null, meaning no lower limit.
- `maxHeight`: the maximum height of the image. Defaults to null, meaning no upper limit.
- `mimeTypes`: a list of file MIME types that are allowed to be uploaded. This can be either an array
or a string consisting of file MIME types separated by space or comma (e.g. "image/jpeg, image/png").
Mime type names are case-insensitive. Defaults to null, meaning all MIME types are allowed.
## [[yii\validators\RangeValidator|in]] <a name="in"></a>
```php
[
// checks if "level" is 1, 2 or 3
['level', 'in', 'range' => [1, 2, 3]],
]
```
This validator checks if the input value can be found among the given list of values.
- `range`: a list of given values within which the input value should be looked for.
- `strict`: whether the comparison between the input value and the given values should be strict
(both the type and value must be the same). Defaults to false.
- `not`: whether the validation result should be inverted. Defaults to false. When this property is set true,
the validator checks if the input value is NOT among the given list of values.
- `allowArray`: whether to allow the input value to be an array. When this is true and the input value is an array,
every element in the array must be found in the given list of values, or the validation would fail.
## [[yii\validators\NumberValidator|integer]] <a name="integer"></a>
```php
[
// checks if "age" is an integer
['age', 'integer'],
]
```
This validator checks if the input value is an integer.
- `max`: the upper limit (inclusive) of the value. If not set, it means the validator does not check the upper limit.
- `min`: the lower limit (inclusive) of the value. If not set, it means the validator does not check the lower limit.
## [[yii\validators\RegularExpressionValidator|match]] <a name="match"></a>
```php
[
// checks if "username" starts with a letter and contains only word characters
['username', 'match', 'pattern' => '/^[a-z]\w*$/i']
]
```
This validator checks if the input value matches the specified regular expression.
- `pattern`: the regular expression that the input value should match. This property must be set,
or an exception will be thrown.
- `not`: whether to invert the validation result. Defaults to false, meaning the validation succeeds
only if the input value matches the pattern. If this is set true, the validation is considered
successful only if the input value does NOT match the pattern.
## [[yii\validators\NumberValidator|number]] <a name="number"></a>
```php
[
// checks if "salary" is a number
['salary', 'number'],
]
```
This validator checks if the input value is a number. It is equivalent to the [double](#double] validator.
- `max`: the upper limit (inclusive) of the value. If not set, it means the validator does not check the upper limit.
- `min`: the lower limit (inclusive) of the value. If not set, it means the validator does not check the lower limit.
## [[yii\validators\RequiredValidator|required]] <a name="required"></a>
```php
[
// checks if both "username" and "password" are not empty
[['username', 'password'], 'required'],
]
```
This validator checks if the input value is provided and not empty.
- `requiredValue`: the desired value that the input should be. If not set, it means the input should not be empty.
- `strict`: whether to check data types when validating a value. Defaults to false.
When `requiredValue` is not set, if this property is true, the validator will check if the input value is
not strictly null; If this property is false, the validator will use a loose rule to determine a value is empty or not.
When `requiredValue` is set, the comparison between the input and `requiredValue` will also check data types
if this property is true.
> Info: How to determine if a value is empty or not is a separate topic covered
in the [Empty Values](input-validation.md#empty-values) section.
## [[yii\validators\SafeValidator|safe]] <a name="safe"></a>
```php
[
// marks "description" to be a safe attribute
['description', 'safe'],
]
```
This validator does not perform data validation. Instead, it is used to mark an attribute to be
a [safe attribute](structure-models.md#safe-attributes).
## [[yii\validators\StringValidator|string]] <a name="string"></a>
```php
[
// checks if "username" is a string whose length is between 4 and 24
['username', 'string', 'length' => [4, 24]],
]
```
This validator checks if the input value
Validates that the attribute value is of certain length.
- `length`: specifies the length limit of the input string being validated. This can be specified
in one of the following forms:
* an integer: the exact length that the string should be of;
* an array of one element: the minimum length of the input string (e.g. `[8]`). This will overwrite `min`.
* an array of two elements: the minimum and maximum lengths of the input string (e.g. `[8, 128]`)`.
This will overwrite both `min` and `max`.
- `min`: the minimum length of the input string. If not set, it means no minimum length limit.
- `max`: the maximum length of the input string. If not set, it means no maximum length limit.
- `encoding`: the encoding of the input string to be validated. If not set, it will use the application's
[[yii\base\Application::charset|charset]] value which defaults to `UTF-8`.
## [[yii\validators\FilterValidator|trim]] <a name="trim"></a>
```php
[
// trims the white spaces surrounding "username" and "email"
[['username', 'email'], 'trim'],
]
```
This validator does not perform data validation. Instead, it will trim the surrounding white spaces around
the input value. Note that if the input value is an array, it will be ignored by this validator.
## [[yii\validators\UniqueValidator|unique]] <a name="unique"></a>
```php
[
// a1 needs to be unique in the column represented by the "a1" attribute
['a1', 'unique'],
// a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
['a1', 'unique', 'targetAttribute' => 'a2'],
// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']],
// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']],
// a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']],
]
```
This validator checks if the input value is unique in a table column. It only works
with [Active Record](db-active-record.md) model attributes. It supports validation against
either a single column or multiple columns.
- `targetClass`: the name of the [Active Record](db-active-record.md) class that should be used
to look for the input value being validated. If not set, the class of the model currently being validated will be used.
- `targetAttribute`: the name of the attribute in `targetClass` that should be used to validate the uniqueness
of the input value. If not set, it will use the name of the attribute currently being validated.
You may use an array to validate the uniqueness of multiple columns at the same time. The array values
are the attributes that will be used to validate the uniqueness, while the array keys are the attributes
whose values are to be validated. If the key and the value are the same, you can just specify the value.
- `filter`: additional filter to be applied to the DB query used to check the uniqueness of the input value.
This can be a string or an array representing the additional query condition (refer to [[yii\db\Query::where()]]
on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
is the [[yii\db\Query|Query]] object that you can modify in the function.
## [[yii\validators\UrlValidator|url]] <a name="url"></a>
```php
[
// checks if "website" is a valid URL. Prepend "http://" to the "website" attribute
// if it does not have a URI scheme
['website', 'url', 'defaultScheme' => 'http'],
]
```
This validator checks if the input value is a valid URL.
- `validSchemes`: an array specifying the URI schemes that should be considered valid. Defaults to `['http', 'https']`,
meaning both `http` and `https` URLs are considered to be valid.
- `defaultScheme`: the default URI scheme to be prepended to the input if it does not have the scheme part.
Defaults to null, meaning do not modify the input value.
- `enableIDN`: whether the validator should take into account IDN (internationalized domain names).
Defaults to false. Note that in order to use IDN validation you have to install and enable the `intl` PHP
extension, otherwise an exception would be thrown.
...@@ -19,15 +19,16 @@ namespace yii\validators; ...@@ -19,15 +19,16 @@ namespace yii\validators;
class DefaultValueValidator extends Validator class DefaultValueValidator extends Validator
{ {
/** /**
* @var mixed a PHP callable returning the default value or the default value to be set to the specified attributes. * @var mixed the default value or a PHP callable that returns the default value which will
* The function signature must be as follows, * be assigned to the attributes being validated if they are empty. The signature of the PHP callable
* should be as follows,
* *
* ~~~ * ```php
* function foo($object, $attribute) { * function foo($model, $attribute) {
* // compute value * // compute value
* return $value; * return $value;
* } * }
* ~~~ * ```
*/ */
public $value; public $value;
/** /**
......
...@@ -37,8 +37,8 @@ class EmailValidator extends Validator ...@@ -37,8 +37,8 @@ class EmailValidator extends Validator
*/ */
public $allowName = false; public $allowName = false;
/** /**
* @var boolean whether to check whether the emails domain exists and has either an A or MX record. * @var boolean whether to check whether the email's domain exists and has either an A or MX record.
* Be aware of the fact that this check can fail due to temporary DNS problems even if the email address is * Be aware that this check can fail due to temporary DNS problems even if the email address is
* valid and an email would be deliverable. Defaults to false. * valid and an email would be deliverable. Defaults to false.
*/ */
public $checkDNS = false; public $checkDNS = false;
......
...@@ -61,7 +61,6 @@ class ExistValidator extends Validator ...@@ -61,7 +61,6 @@ class ExistValidator extends Validator
* is the [[\yii\db\Query|Query]] object that you can modify in the function. * is the [[\yii\db\Query|Query]] object that you can modify in the function.
*/ */
public $filter; public $filter;
/** /**
* @var boolean whether to allow array type attribute. * @var boolean whether to allow array type attribute.
*/ */
......
...@@ -52,10 +52,10 @@ class ImageValidator extends FileValidator ...@@ -52,10 +52,10 @@ class ImageValidator extends FileValidator
*/ */
public $maxHeight; public $maxHeight;
/** /**
* @var array|string a list of file mime types that are allowed to be uploaded. * @var array|string a list of file MIME types that are allowed to be uploaded.
* This can be either an array or a string consisting of file mime types * This can be either an array or a string consisting of file MIME types
* separated by space or comma (e.g. "image/jpeg, image/png"). * separated by space or comma (e.g. "image/jpeg, image/png").
* Mime type names are case-insensitive. Defaults to null, meaning all mime types * Mime type names are case-insensitive. Defaults to null, meaning all MIME types
* are allowed. * are allowed.
* @see wrongMimeType * @see wrongMimeType
*/ */
......
...@@ -76,6 +76,7 @@ class Validator extends Component ...@@ -76,6 +76,7 @@ class Validator extends Component
'trim' => [ 'trim' => [
'class' => 'yii\validators\FilterValidator', 'class' => 'yii\validators\FilterValidator',
'filter' => 'trim', 'filter' => 'trim',
'skipOnArray' => true,
], ],
'unique' => 'yii\validators\UniqueValidator', 'unique' => 'yii\validators\UniqueValidator',
'url' => 'yii\validators\UrlValidator', 'url' => 'yii\validators\UrlValidator',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment