A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.yiiframework.com/doc/guide/2.0/en/tutorial-core-validators below:

Special Topics: Core Validators | The Definitive Guide to Yii 2.0

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:

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.

boolean
[
    
    ['selected', 'boolean'],

    
    ['deleted', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true],
]

This validator checks if the input value is a boolean.

Note: Because data input submitted via HTML forms are all strings, you normally should leave the strict property as false.

captcha
[
    ['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 CAPTCHA widget.

compare
[
    
    ['password', 'compare'],

    
    ['password', 'compare', 'compareAttribute' => 'password_repeat'],

    
    ['age', 'compare', 'compareValue' => 30, 'operator' => '>=', 'type' => 'number'],
]

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

Comparing date values

The compare validator can only be used to compare strings and numbers. If you need to compare values like dates you have two options. For comparing a date against a fixed value, you can simply use the date validator and specify its $min or $max property. If you need to compare two dates entered in the form, e.g. a fromDate and a toDate field, you can use a combination of compare and date validator like the following:

['fromDate', 'date', 'timestampAttribute' => 'fromDate'],
['toDate', 'date', 'timestampAttribute' => 'toDate'],
['fromDate', 'compare', 'compareAttribute' => 'toDate', 'operator' => '<', 'enableClientValidation' => false],

As validators are executed in the order they are specified this will first validate that the values entered in fromDate and toDate are valid date values and if so, they will be converted into a machine-readable format. Afterwards these two values are compared with the compare validator. Client validation is not enabled as this will only work on the server-side because the date validator currently does not provide client validation, so $enableClientValidation is set to false on the compare validator too.

date

The date validator comes with three different shortcuts:

[
    [['from_date', 'to_date'], 'date'],
    [['from_datetime', 'to_datetime'], 'datetime'],
    [['some_time'], 'time'],
]

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 or other machine readable format and store it in an attribute specified via timestampAttribute.

In case the input is optional you may also want to add a default value filter in addition to the date validator to ensure empty input is stored as null. Otherwise, you may end up with dates like 0000-00-00 in your database or 1970-01-01 in the input field of a date picker.

[
    [['from_date', 'to_date'], 'default', 'value' => null],
    [['from_date', 'to_date'], 'date'],
],
default
[
    
    ['age', 'default', 'value' => null],

    
    ['country', 'default', 'value' => 'USA'],

    
    [['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.

function foo($model, $attribute) {
    
    return $value;
}

Info: How to determine if a value is empty or not is a separate topic covered in the Empty Values section. Default value from database schema could be loaded via loadDefaultValues() method of the model.

double
[
    
    ['salary', 'double'],
]

This validator checks if the input value is a double number. It is equivalent to the number validator.

each

Info: This validator has been available since version 2.0.4.

[
    
    ['categoryIDs', 'each', 'rule' => ['integer']],
]

This validator only works with an array attribute. It validates if every element of the array can be successfully validated by a specified validation rule. In the above example, the categoryIDs attribute must take an array value and each array element will be validated by the integer validation rule.

Note: If the attribute value is not an array, it is considered validation fails and the message will be returned as the error message.

email
[
    
    ['email', 'email'],
]

This validator checks if the input value is a valid email address.

exist
[
    
    
    ['a1', 'exist'],
    
    ['a1', 'exist', 'targetAttribute' => 'a1'],
    ['a1', 'exist', 'targetAttribute' => ['a1' => 'a1']],

    
    
    ['a1', 'exist', 'targetAttribute' => 'a2'],
    
    ['a1', 'exist', 'targetAttribute' => ['a1' => 'a2']],
    
    
    
    ['a1', 'exist', 'targetAttribute' => ['a2']],
    
    ['a1', 'exist', 'targetAttribute' => ['a2' => 'a2']],

    
    
    [['a1', 'a2'], 'exist', 'targetAttribute' => ['a1', 'a2']],
    
    [['a1', 'a2'], 'exist', 'targetAttribute' => ['a1' => 'a1', 'a2' => 'a2']],

    
    
    ['a1', 'exist', 'targetAttribute' => ['a1', 'a2']],
    
    ['a1', 'exist', 'targetAttribute' => ['a1' => 'a1', 'a2' => 'a2']],

    
    
    ['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']],
    
    ['a1', 'exist', 'targetAttribute' => ['a2' => 'a2', 'a1' => 'a3']],

    
    
    
    ['a1', 'exist', 'allowArray' => true],
    
    
    
    ['type_id', 'exist', 'targetClass' => ProductType::class, 'targetAttribute' => ['type_id' => 'id']],    
    
    
    ['type_id', 'exist', 'targetRelation' => 'type'],
]

This validator checks if the input value can be found in a table column represented by an Active Record attribute. You can use targetAttribute to specify the Active Record attribute and targetClass the corresponding Active Record class. If you do not specify them, they will take the values of the attribute and the model class being validated.

You can use this validator to validate against a single column or multiple columns (i.e., the combination of multiple attribute values should exist). In case of validation fail on the multiple columns checked at the same time (like ['a1', 'a2'] in the examples) and skipOnError set to true, only the first attribute without any previous errors will receive a new error message.

file
[
    
    
    ['primaryImage', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024*1024],
]

This validator checks if the input is a valid uploaded file.

FileValidator is used together with yii\web\UploadedFile. Please refer to the Uploading Files section for complete coverage about uploading files and performing validation about the uploaded files.

filter
[
    
    [['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],

    
    ['phone', 'filter', 'filter' => function ($value) {
        
        return $value;
    }],
    
    
    ['phone', 'filter', 'filter' => [$this, 'normalizePhone']],
    
    public function normalizePhone($value) {
        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.

Tip: If you want to trim input values, you may directly use the trim validator.

Tip: There are many PHP functions that have the signature expected for the filter callback. For example to apply type casting (using e.g. intval, boolval, ...) to ensure a specific type for an attribute, you can simply specify the function names of the filter without the need to wrap them in a closure:

['property', 'filter', 'filter' => 'boolval'],
['property', 'filter', 'filter' => 'intval'],
image
[
    
    ['primaryImage', 'image', 'extensions' => '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 validator and thus inherits all its properties. Besides, it supports the following additional properties specific for image validation purpose:

ip
[
    
    ['ip_address', 'ip'],

    
    
    ['ip_address', 'ip', 'ipv4' => false, 'subnet' => null, 'expandIPv6' => true],

    
    
    ['ip_address', 'ip', 'negation' => true],
]

The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet. It also may change attribute's value if normalization or IPv6 expansion is enabled.

The validator has such configuration options:

Info: This validator has been available since version 2.0.7.

in
[
    
    ['level', 'in', 'range' => [1, 2, 3]],
]

This validator checks if the input value can be found among the given list of values.

integer
[
    
    ['age', 'integer'],
]

This validator checks if the input value is an integer.

match
[
    
    ['username', 'match', 'pattern' => '/^[a-z]\w*$/i']
]

This validator checks if the input value matches the specified regular expression.

number
[
    
    ['salary', 'number'],
]

This validator checks if the input value is a number. It is equivalent to the double validator.

required
[
    
    [['username', 'password'], 'required'],
]

This validator checks if the input value is provided and not empty.

Info: How to determine if a value is empty or not is a separate topic covered in the Empty Values section.

safe
[
    
    ['description', 'safe'],
]

This validator does not perform data validation. Instead, it is used to mark an attribute to be a safe attribute.

string
[
    
    ['username', 'string', 'length' => [4, 24]],
]

This validator checks if the input value is a valid string with certain length.

trim
[
    
    [['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.

unique
[
    
    
    ['a1', 'unique'],
    
    ['a1', 'unique', 'targetAttribute' => 'a1'],
    ['a1', 'unique', 'targetAttribute' => ['a1' => 'a1']],

    
    
    ['a1', 'unique', 'targetAttribute' => 'a2'],
    
    ['a1', 'unique', 'targetAttribute' => ['a1' => 'a2']],

    
    
    [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']],
    
    [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1' => 'a1', 'a2' => 'a2']],

    
    ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']],

    
    
    ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']],
    
    
    
    ['type_id', 'unique', 'targetClass' => ProductType::class, 'targetAttribute' => 'id'],    
]

This validator checks if the input value is unique in a table column. It only works with Active Record model attributes. It supports validation against either a single column or multiple columns. In case of validation fail on the multiple columns checked at the same time (like ['a1', 'a2'] in the examples) and skipOnError set to true, only the first attribute without any previous errors will receive a new error message.

url
[
    
    
    ['website', 'url', 'defaultScheme' => 'http'],
]

This validator checks if the input value is a valid URL.

Note: The validator checks that URL scheme and host part is correct. It does NOT check the remaining parts of a URL and is NOT designed to protect against XSS or any other attacks. See Security best practices article to learn more about threats prevention when developing applications.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4