Yii core validators api details, yii core api details

Source: Internet
Author: User
Tags idn mx record

Yii core validators api details, yii core api details

This article describes the Yii core validator api. We will share this with you for your reference. The details are as follows:

Core Validators

Preface

Yii provides a series of common core validators that you can
Yii \ validators namespace is found. Long validators class names are not used, and you can replace them with aliases.

For example, you can use the alias required to replace the yii \ validators \ RequiredValidator class:

<?phppublic function rules(){  return [    [['email', 'password'], 'required'],  ];}?>

This yii \ validators \ Validator: $ builtInValidators attribute contains aliases of all supported validators.

Next, we will explain the usage of each core validator.

1. boolean-to-error value

<? Php [// check whether "selected" is 0 or 1, regardless of the Data Type ['selected', 'boolean'], // check whether "deleted" is a boolean type, it can only be true or false ['deleted', 'boolean', 'truevalue '=> true, 'falsevalue' => false, 'strict' => true],]?>

Check whether it is a bool value.

TrueValue: indicates the value of true. The default value is '1 '.
FalseValue: indicates the value of false. The default value is '0 '.
Strict: whether the value in the input box must match the set trueValue and falseValue. The default value is false.

Note: because the data submitted in HTML format is character-based, you need to set the strict attribute to false.

2. captcha Verification Code

<?php[  ['verificationCode', 'captcha'],]?>

This validators usually
Yii \ captcha \ CaptchaAction and
Yii \ captcha \ Captcha are used together to ensure that the same verification code is entered through the CAPTCHA component.
CaseSensitive: whether the verification code is case sensitive. The default value is false.
CaptchaAction: the path of the CAPTCHA image generated by the CAPTCHA action of the default verification code. The default value is 'site/captcha '.
SkipOnEmpty: whether to skip verification when the input is null. The default value is false, indicating that the input is required.

3. compare comparison

<? Php [// verify whether the "password" attribute is equal to "password_repeat" ['Password', 'compare '], // verify that age> = 30 ['age ', 'compute', 'compute' => 30, 'operator' => '> ='],]?>

This validator compares the specified input value with another value to ensure that the specified operator is used between them.

CompareAttribute: Who will the attribute name be compared. when the validator is used to verify an attribute, it will be compared with the attribute with the same name but with the suffix _ repeat. for example, if the property name to be verified is password, the default property name for comparison is password_repeat. You can specify the value you want.
CompareValue: a constant value compared with the input value. This value takes precedence when the property and compareAttribute attributes are both specified.
Operator: the operator to be compared. The default value is =, that is, the input value is equal to the value of compareAttribute or compareValue.
The following operators are supported: =, =, and ,! = ,! =,>,> =, <, <=.

4. date

<?php[  [['from_date', 'to_date'], 'date'],]?>

This validator checks that the input value is a date, time, or datetime in a proper form. (Optional) converts the input value to a UNIX Timestamp and stores it in an attribute specified by timestampAttribute.

Format: this date/time is all supported formats declared in the http://php.net/manual/en/datetime.createfromformat.php

If this value is not set, Yii: $ app-> formatter-> dateFormat is automatically set.
TimestampAttribute: attribute name is used to store the date or time that the conversion will input. it can also be the same property name that has been verified. in this case, the original value will be overwritten by the timestamp. you can see the example of "how to process the date selector DatePicker.
Http://www.yiiframework.com/doc-2.0/widget-jui#datepicker-date-input

If the input is optional, you may also need to add a default filter in addition to date verification to ensure that the NULL input is stored as NULL. Otherwise you may eventually get the date like the input field of the date selector at 0000-00-00 or your database 1970-01-01.

<?php[  [['from_date', 'to_date'], 'default', 'value' => null],  [['from_date', 'to_date'], 'date'],],?>

5. default Value

<? Php [// set "age" to null if it is null ['age', 'default', 'value' => null], // set "country" to "USA" if it is null ['country', 'default', 'value' => 'usa'], // assign "from" and "to" three days and six days respectively. If they are empty, ['from', 'to'], 'default ', 'value' => function ($ model, $ attribute) {return date ('Y-m-d', strtotime ($ attribute = 'to '? '+ 3 days': '+ 6 days');}],]?>

The validators do not validate data. When they are empty, the property value is assigned.

Value: the default function prototype of the form is as follows,

<? Phpfunction foo ($ model, $ attribute) {//... assemble $ value... return $ value ;}?>

6. double Floating Point Value

<? Php [// check that "salary" is a double number ['salary ', 'double'],]?>

It is equivalent to a digital validator:

Max: maximum number. No check is set.
Min: The number is offline. If no value is set, no check is performed.

7. email Verification

<? Php [// check the email address as a valid "email" Address ['email ', 'email'],]?>

AllowName: Check whether the name is allowed to appear in the mailbox (e.g. John Smith <john.smith@example.com>). The default is false.
CheckDNS: whether to check whether the email domain name exists and whether there is any A or MX record. Please note that this check may fail due to temporary DNS issues, even if the email address is actually valid. The default value is false.
EnableIDN, whether the IDN (International Domain Name) should be taken into account during the verification process ). The default value is false. Note that to use IDN for verification, you must install and enable the International PHP extension, or an exception will be thrown.

8. exist

<? Php [// a1 requires "a1" in the attribute column. It seems that ['a1', 'exist'], // a1 exists by default, however, its value uses A2 to check whether ['a1', 'exist', 'targetattribute' => 'a2 '] exists. // both a1 and a2 must exist, they will all receive error messages [['a1', 'a2 '], 'exist', 'targetattribute' => ['a1', 'a2'], // a1 and a2 must exist at the same time. Only a1 will receive the error message ['a1', 'exist', 'targetattribute' => ['a1', 'a2 '], // a1 must exist through detection of a2 and a3 (with a1 value) ['a1', 'exist', 'targetattribute' => ['a2 ', 'a1' => 'a3 '], // a1 needs to be stored If a1 is an array, each element must exist. ['a1', 'exist', 'allowarray' => true],]?>

This validator checks whether the input value can be found in the column value of the corresponding table. It only works in the attribute of the Active Record model.

It supports validation of single or multiple columns

TargetClass: Specifies the name of the Active Record class used for input value verification. If not set, the current model class is used by default.
TargetAttribute: it should be used to verify the name of the property of the input value that exists in targetClass. If this parameter is not set, the name of the property currently being verified is used. You can use arrays to verify the existence of multiple columns simultaneously. The value of the array is used to verify the existing attribute, and the array key is the attribute whose value is to be verified. If the keys and values are the same, you can specify the values.
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 Query object that you can modify in the function.
AllowArray: whether the input value is an array. the default value is false. if the attribute is true and the input is an array, every element must exist in the target column. note that this attribute cannot be set to true. If you want to verify multiple columns, set targetAttribute to an array.

9. file Verification

<? Php [// check that the format of the file Uploaded By "primaryImage" is PNG, JPG, or GIF // the file size must be less than 1 MB ['primaryimag', 'file ', 'extension' => ['png ', 'jpg', 'gif'], 'maxsize' => 1024*1024],]?>

Check whether a valid file is uploaded.

Extensions: List of file types that can be uploaded. it can be an array or a string separated by commas. "gif, jpg "). the extension is case-insensitive. The default value is null, which means all file extensions are allowed.
MimeTypes: media type of file resources that can be uploaded. It can be an array or a string separated by commas or spaces (such. "image/jpeg, image/png "). case-insensitive. The default value is null, which means all file extensions are allowed.
MinSize: the minimum number of bytes of the uploaded file is not set.
MaxSize: the maximum number of bytes of the uploaded file is not set.
MaxFiles: the maximum number of uploaded files is 1 by default, which means that only one file can be uploaded. If the number of uploaded files is greater than 1, the input must be an array containing up to the maximum number of maxFiles.
CheckExtensionByMimeType: whether to check the file extension. If the extension generated by the MIME type check is different from the uploaded file extension, the file will be considered invalid. The default value is true.
FileValidator and yii \ web \ UploadedFile are used together ..

File Upload see http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

10. filter Filtering

<? Php [// remove "username" and "email" and enter spaces to skip array verification [['username', 'email '], 'filter ', 'filter' => 'trim', 'skiponarray' => true], // verify normal "phone" input ['phone', 'filter ', 'filter' => function ($ value) {// mobile phone code return $ value;}],]?>

The validators cannot verify the data. on the contrary, it applies a filter on the input value and assigns it back to the attribute being validated.

Filter: a php callback function defines a filter. It may be the name of a global function, an anonymous function, etc. The prototype of the function must be <? Php function ($ value) {return $ newValue;}?> This attribute must be set.

SkipOnArray: whether to skip an array when the input is only an array. The default value is false. Note that if the filter cannot process the array input, set this attribute to true. Otherwise, some PHP errors may occur.

TIPS: Use trim for verification directly by removing spaces.

TIPS: some packages can directly use system functions such as intval:

<?php['property', 'filter', 'filter' => 'boolval'],['property', 'filter', 'filter' => 'intval'],?>

11. image

<? Php [// check whether "primaryImage" is a valid image and the size is suitable ['primaryimag', 'image', 'extension' => 'png, jpg ', 'minwidth' => 100, 'maxwidth' => 1000, 'minheight' => 100, 'maxheight' => 1000,],]?>

Extension of file validators:

MinWidth: The minimum width is not limited.
MaxWidth: the maximum width is not limited.
MinHeight: the minimum height is not limited.
MaxHeight: the maximum height is not limited.

12. The value of in that Array

<? Php [// check if "level" is 1, 2, or 3 ['level', 'in', 'range' => [1, 2, 3],]?>

Check whether the input value exists in the list of given series values.

Range: the list of given range values.
Strict: whether the comparison result between the input value and the given value should be strict (the type and value must be the same ). The default value is false.
Not: whether the verification result should be reversed. The default value is false. When this attribute is set to true, the verification check and the input value cannot be the value of the given list.
AllowArray: whether the input value is an array. If this is true and the input value is an array, it is found in the given list of values required for each element in the array, or verification fails.

13. integer Verification

<? Php [// check if "age" is an integer value ['age', 'integer'],]?>

Max: the maximum value is not checked.
Min: no check for the lower limit ..

14. match Regular Expression matching check

<? Php [// check that "username" starts with a letter and only contains the character ['username', 'match ', 'pattern' => '/^ [a-z] \ w * $/I']?>

The regular expression matching check specified by the input value.

Pattern: the rule that the input value must match. The attribute must be set. Otherwise, an exception is thrown.
Not: whether to reverse the verification result. The default value is false.

15. number check

<? Php [// check that "salary" is a number ['salary ', 'number'],]?>

It is equivalent to the double validators.

Max: the maximum value is not checked.
Min: no check is performed for the lower limit.

16. Check whether required is empty

<? Php [// check if "username" and "password" are not empty [['username', 'Password'], 'required'],]?>

The validators prevent users from submitting empty form data.

RequiredValue: the value to be input. If not set, the input value should not be blank.
Strict: whether to check the data type when verifying a value. the default value is false. when requiredValue is not set, if this attribute is true, the validator checks that the input value is not strictly null. If the attribute is set to false, the validators will use a loose rule to determine whether a value is null or not. when requiredValue is set, the comparison between the input and requiredValue will also check the data type if this attribute is true.

17. safe indicates that the input is a security attribute.

<? Php [// mark "description" as a safe attribute ['description', 'safe '],]?>

This validator does not perform data verification. On the contrary, it is used to mark the attribute as a Security Attribute (I guess it does not escape characters ).

18. string Verification

<? Php [// check that "username" is a string and the length is between 4 and 24 ['username', 'string', 'length' => [4, 24],]?>

This validator checks that the input value is a string and the length is within the range of a specified value.

Length: specify the length of the string to be verified. You can specify the following format:
An integer: the exact length of a string;
Single array element: the input minimum length (e.g. [8]). must exceed or equal to this number
Two array elements: the minimum length and maximum length of the input (e.g. [8,128]).
Min: the minimum length of the input string is not limited.
Max: the maximum length of the input string is not limited ..
Encoding: the encoding of the input string is not set to the default UTF-8.

19. trim remove space

<? Php [// remove the spaces on both sides of "username" and "email" [['username', 'email '], 'trim'],]?>

If the attribute is an array, the filter is automatically ignored.

20. unique uniqueness Verification

<? Php [// a1 must be unique ['a1', 'unique'] In the column represented by the "a1" attribute. // a1 must be unique, however, column a2 will be used to check the uniqueness of the a1 value ['a1', 'unique', 'targetattribute' => 'a2 '], // a1 and a2 must be unique, and all of them will receive the error message [['a1', 'a2 '], 'unique ', 'targetattribute' => ['a1', 'a2 '], // a1 and a2 must be unique. Only A_1 will receive the error message ['a1 ', 'unique', 'targetattribute' => ['a1', 'a2 '], // the uniqueness of the two a2 and a3 to be checked by a1 (the a1 value is used) is the only ['a1', 'unique', 'targetattribute' => ['a2 ', 'a1' => 'a3'],]?>

This verification check, if the input value is unique in the table column. It applies only to the attributes of the activity record model. It supports verification on any single column or multiple columns.

TargetClass: the name of the activity record class used to verify the input value. If no value is set, the class to be used is currently verifying the model.
TargetAttribute: it should be used to verify that the input value is unique in the name of the targetClass attribute. If this parameter is not set, the name of the property currently being verified is used. You can use arrays to verify the uniqueness of multiple columns at the same time. The value of an array is the attribute that will be used to verify uniqueness, and the array key is the attribute whose value is to be verified. If the keys and values are the same, you can specify the values.
Filter: an additional filter is applied to the database query used to check the uniqueness of the input value. This can be a string or an array that represents an additional Query condition (refer to the format of the yii \ db \ Query: where () Query condition), or an anonymous function image: function ($ query), where $ query is the query object that you can modify in the function.
Http://www.yiiframework.com/doc-2.0/yii-db-query.html#where ()-detail

21. url address verification

<? Php [// check "website" is a valid URL. prefix "http: //" to "website" attributes // if it does not have a URI mode ['website', 'url ', 'defaultscheme '=> 'HTTP'],]?>

ValidSchemes: An array specified URI scheme should be considered valid. The default value is ['http', 'https'], indicating that HTTP and HTTPS URLs are considered valid.
DefaultScheme: the default URI scheme should take into account the input in advance if it does not have a part of the scheme. The default value is null, which means that the input value is not modified.
EnableIDN: Verify whether IDN (international domain name) is taken into account ). The default value is false. Note that to use IDN for verification, you must install and enable the International PHP extension. Otherwise, an exception will be thrown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.