Yii Learning Note Five (core Validator API translation)

Source: Internet
Author: User
Tags html form idn mx record yii

Kernel Authenticator core validators

0. Preface
YII provides a series of Common Core validators that you can
Found in yii\validators namespace . Instead of using long validator class names, you can replace them with aliases.

For example, you can use alias required instead of the Yii\validators\requiredvalidator class:

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

this yii\validators\validator:: $builtInValidators attribute the alias of all supported validators for life.

Next, we'll explain the usage of each of the core validators.

1. Boolean error value

<?php[    //Check whether "selected" is 0 or 1 regardless of data type    [' Selected ', ' Boolean '],    //check whether "deleted" is a Boolean type and can only be TR UE or False    [' Deleted ', ' Boolean ', ' truevalue ' = = True, ' falsevalue ' = False, ' strict ' = = true],]?>

the above detects if it is a bool value.

TrueValue: Represents the value when true. The default is ' 1 '.
Falsevalue: Represents the value when false. The default is ' 0 '.
Strict: Whether the value in the input box must match the settings of TrueValue and Falsevalue. The default is False.
Note: Because the data submitted through HTML form are all character A, you generally need to set the strict property to false.


2. Captcha Verification Code

<?php[    [' Verificationcode ', ' Captcha '],]?>

This validator is usually
yii\captcha\captchaaction and
Yii\captcha\captcha is used together to ensure that the input is the same as the CAPTCHA through the CAPTCHA component.

casesensitive: Whether the verification code needs to be case sensitive. The default is False.
captchaaction: The CAPTCHA action of the default CAPTCHA generates the path to the CAPTCHA image. The default is ' Site/captcha '.
Skiponempty: Whether to skip validation when the input is empty. The default is False, which is required for input inputs.


3. Compare comparison

<?php[    //Verify if the "password" attribute and "password_repeat" are equal    [' password ', ' compare '],    //Verify Age >=    [' Age ', ' compare ', ' comparevalue ' and ' = ', ' operator ' and ' >= '],]?>

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

Compareattribute: The name of the property is about to be compared with whom. When the validator is used to validate a property, he will have the same name as the property.
But the attributes with the suffix _repeat are compared. For example, if the property name you want to verify is password, then the default comparison property name is Password_repeat you can specify the value you want.

comparevalue: A constant value that is compared to the input value. This value takes precedence when the property and Compareattribute properties are specified at the same time.
operator: the comparison operator. The default is = =, which succeeds when the input value is equal to the Compareattribute or CompareValue value.
The following operators are supported: = =, = = =, =,!==, >, >=, <, <=.


4. Date Dates

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

This validator checks that the input value is a date, time, or DateTime in a suitable form. Optionally, he can convert the input value into a UNIX timestamp stored in a property specified by Timestampattribute .

format: This date/time is a supported format declared in http://php.net/manual/en/datetime.createfromformat.php
If this value is not set, he will automatically fetch the value Yii:: $app->formatter->dateformat.
Timestampattribute: The property name is used to store the date or time that the transformation will enter. It can also be the same property name as being validated. If this is the case, the original value will be rewritten by the timestamp. You can look at "How to handle date picker DatePicker" with examples.
Http://www.yiiframework.com/doc-2.0/widget-jui#datepicker-date-input

If the input is optional, you may also want to add a default filter in addition to the date validation to ensure that the empty input store is null. Otherwise you may end up getting
Date like the date selector for the input field in 0000-00-00 or your database 1970-01-01.

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

5.default Default Value

<?php[    //Set "age" to null if he is empty    [' age ', ' Default ', ' value ' = null],    //Set "country" to "USA" if he is empty 
   
    [' country ', ' Default ', ' value ' = ' USA '],    //Assign "from" and "to" Add 3 days and 6 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 ');    }],]?>
   

This validator does not validate the data. When they are empty. Assigned to a property value.

value: The default function prototype for the form is as follows,

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

6. Double floating-point value

<?php[    //Check "salary" is a double number    [' Salary ', ' double '],]?>

Equivalent to a digital validator:

Max: Number limit, not set not checked
min: Digital downline, not set not checked


7. Email Email Verification

<?php[    //Check mailbox is a valid "email" address    [' email ', ' email '],]?>

allowname: Check whether the name is allowed to appear in the mailbox (e.g. John Smith <[email protected]>). The default is False.
Checkdns, check whether the domain name of the e-mail is present, and whether there is any a or MX record. Note that this may be checked because of a temporary DNS issue that fails even if the e-mail address is actually valid. The default is False.
ENABLEIDN, the validation process should take into account IDNs (internationalized domain names). The default is False. It is important to note that in order to use IDN authentication you must install and enable international PHP extensions, or exceptions will be thrown.

8. Does the exist exist

<?php[    //A1 need to exist in the attribute column "A1" This seems to have a default of Ah     [' A1 ', ' exist '],    //A1 exist, but its value will use A2 to check whether there is    [' A1 ', ' Exist ', '  Targetattribute ' + ' A2 '],    //A1 and A2 need to exist at the same time, they will receive error messages    [[' A1 ', ' A2 '], ' exist ', ' targetattribute ' = [' A1 ', ' A2 '],    //A1 and A2 need to exist simultaneously, only A1 will receive error Messages    [' A1 ', ' exist ', ' targetattribute ' = [' A1 ', ' A2 ']],    //A1 need to exist through Detection of A2 and A3 (values with A1)    [' A1 ', ' exist ', ' targetattribute ' = [' A2 ', ' a1 ' = ' A3 ']],    //A1 need to exist. If A1 is an array, then every must exist for each element.    [' A1 ', ' exist ', ' allowarray ' = true],]?>

This validator checks that the input value can be found in the column values of the corresponding table, and he will only function in the properties of the Active Record model.
He supports validating single-column or multicolumn

targetclass : The name of the Active Record class used to look for validation of input values. If not set, The model class that is currently set is used by default.
targetattribute : The name of the property that should be used to validate the presence of the input value in Targetclass. If not set, the name of the property that is currently being validated is used. Arrays can be used to verify the existence of multiple columns at the same time. The value of the array is the property that will be used to validate the existence, and the array key is the property whose value is to be validated. If the keys and values are the same, you can specify a value.
filter : Additional filter to BES applied to the DB query used to check the existence of the input value. This can is 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 are the query object that You can modify in the function.
allowarray : The value entered is an array. Default false. If the property is true and the input is an array, Well, then, every element here must exist in the target column to which it is directed. Note that this property cannot be set to True if you set the validation multi-column by setting Targetattribute to an array.

9. File Validation

<?php[//    check "primaryimage" uploaded file format is PNG, JPG or GIF    //The file size must is less than 1MB    [' Primaryimage ' , ' file ', ' extensions ' = [' png ', ' jpg ', ' gif '], ' maxSize ' + 1024*1024],]?>

Check to see if it is a valid upload file.

Extensions: List of file types that are allowed to be uploaded. He can be an array or a comma-separated
The cut string (such as. "GIF, JPG"). The extension is case-insensitive and defaults to NULL, which means that all file extensions are allowed.
mimetypes: The media type of the file resource that is allowed to be uploaded. He could be an array or a
A string separated by commas or spaces (such as. "Image/jpeg, Image/png"). Case-insensitive, the default is null, which means that all file extensions are allowed.
minSize: The minimum number of bytes to upload a file is not set to be judged.
maxSize: The maximum number of bytes to upload file is not set to be judged.
Maxfiles: The maximum number of uploaded files by default is 1, which means you can only upload individual files for a single file upload box. If it is greater than 1, then input must be an array containing up to maxfiles of uploaded files.
Checkextensionbymimetype: Whether to check the file extension. If the extension generated by the MIME type check is different from the uploaded file name extension, the file will be considered invalid. The default value is true, meaning that this check is done.
Filevalidator and Yii\web\uploadedfile are used together. .

File upload please refer to: http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

Filter Filtering

<?php[    //Remove "username" and "email" input space to skip the group verification    [[' username ', ' email '], ' filter ', ' filter ' = ' trim ', ' Skipona Rray ' + true],    //verify normal "phone" input    [' phone ', ' filter ', ' filter ' = function ($value) {        //Verify correctness of phone code        return $value;    }],]?>

This validator does not validate the data. Instead, 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. He may be the name of a global function, an anonymous function, and so on.  The prototype of the function must be <?php function ($value) {return $newValue;} ?> This property must be set.

Skiponarray: Whether to skip when the input is just an array. The default is False. Note that you should set this property to True if the filter cannot handle the array input. Otherwise, some PHP errors may occur.

Tip: Go to the blanks directly with trim verification.
Tip: Partial encapsulation can be used directly with system functions such as Intval:

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

One . Image Image

<?php[    //Check if "Primaryimage" is a valid picture and size appropriate    [' primaryimage ', ' image ', ' extensions ' = ' png, jpg ',        ' MinWidth ' = ' +, ' maxWidth ' = ' + ',        ' minheight ', ' maxheight ' + +,    ],]?>

extension of File verifier:

minWidth: The minimum width is unlimited.
maxWidth: The maximum width is unlimited.
minheight: The minimum height is unlimited.
maxheight: Maximum height is unlimited.


the values in that array

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

checks whether the input value exists in the list for the given series value.

Range: A list of values for a given range.
Strict: Whether the comparison between the input value and the given value should be strict (the type and value must be the same). The default is False.
not: Verify that the results should be reversed. The default is False. When this property is set to True, validation checks that the input value cannot be in the value of the given list.
Allowarray: Whether the input value is allowed is an array. If this is true, and the input value is an array, each element in the array must be found in the given list of values, or the validation will fail.


integer integer Validation

<?php[    //Check "age" is an integer value    [' Age ', ' Integer '],]?>

Max: The upper limit is not checked.
min: The lower limit is not set to check.

Match regular matching check

<?php[    //check "username" begins with a letter and contains only literal    characters [' username ', ' match ', ' pattern ' = '/^[a-z]\w*$/i ']]?>

The input value specifies the regular expression match validation check.

Pattern: The input value must match the rule. The property must be set, or an exception will be thrown.
not: Reverses the validation result. False by default.

. Number Check

<?php[    //Check "salary" is a number    [' salary ', ' numbers '],]?>
equivalent to a double validator.

Max: The upper limit is not checked.
min: The lower limit is not set to check.

required whether the check is empty

<?php[    //check "username" and "password" are not empty    [[' Username ', ' password '], ' required '],]?>
The validator prevents users from submitting empty form data.

requiredvalue: The value that should be entered. If not set it means that the input value should not be empty.
Strict: Whether the data type should be checked when validating a value. The default is False. When Requiredvalue is not set, if this property is true, the validator checks that the input value is not strictly null, and if the property is False, the validator uses a loose rule to determine whether a value is empty or not. When Requiredvalue is set, the comparison between the input and the Requiredvalue will also check the data type if this property is true.

safe Tag Input is a security attribute

<?php[    //Mark "description" is a safe attribute    [' description ', ' Safe '],]?>
This validator does not perform data validation. Instead, it is used to mark the property as a security attribute (I guess the function is not to do character escapes).


. String string Validation

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

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

Length: Specifies how long to validate the string. You can specify the following form:
An integer: The exact length of the string;
Single array element: the minimum length of the input (e.g. [8]). must be greater than or equal to this number
Two array elements: the minimum and maximum length of the input (e.g. [8, 128]).
min: The minimum length of the input string is not set to unlimited.
Max: The maximum length of the input string is not set to No limit .
Encoding: The encoding of the input string is not set to the default UTF-8.

trim de-whitespace

<?php[    //Remove "username" and "email" on both sides of the space    [[' username ', ' email '], ' trim '],]?>

Do not validate data only go to whitespace if the property is an array it will automatically ignore this filter.

Unique Uniqueness Verification

<?php[    //A1 needs to be unique in the column represented by the "A1" attribute    [' A1 ', ' Unique '],    //A1 must 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, and they will all receive error messages    [[' A1 ', ' A2 '], ' unique ', ' targetattribute ' = [' A1 ', ' A2 '],    //  A1 and A2 need to be unique, only A1 will receive error Messages    [' A1 ', ' Unique ', ' targetattribute ' = [' A1 ', ' A2 ']],    //A1 need to check the uniqueness of the two A2 and A3 (using the value of A1) is unique    [' A1 ', ' Unique ', ' targetattribute ' = [' A2 ', ' A1 ' and ' A3 ']],]?>

This validation checks if the input value is unique in the table column. It applies only to the properties of the active record model. It supports validating against any single column or multiple columns.

Targetclass: The name of the activity record class that should be used to verify the lookup input value. If not set, the class that will be used is currently validating the model.
Targetattribute: The name of the property that should be used to verify the uniqueness of the input value in Targetclass. If not set, the name of the property that is currently being validated is used. Arrays can be used to verify the uniqueness of multiple columns at the same time. The value of the array is the property that will be used to verify uniqueness, and the array key is the property whose value is to be validated. If the keys and values are the same, you can specify the values.
Filter: A additional filter is applied to the database query that is used to check the uniqueness of the input values. 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 like: function ($query), where $query is where you can modify the query object.
Http://www.yiiframework.com/doc-2.0/yii-db-query.html#where ()-detail


URL Address Verification

<?php[//    Check "website" is a valid URL. Front "http:/" to "website" Property    //If it does not have a URI pattern    [' website ', ' URL ', ' default Scheme ' = ' http '],]?>

validschemes: An array specifies that the URI scheme should be considered valid. The default is [' http ', ' HTTPS '], which means that the HTTP and HTTPS URLs are considered valid.
defaultscheme: The default URI scheme is to pre-consider the input if it does not have a part of the scheme. The default is null, which means that the input value is not modified.
ENABLEIDN: Verify that IDN (internationalized domain names) should be considered. The default is False. It should be noted that in order to use IDN authentication you must install and enable international PHP extensions, otherwise exceptions will be thrown.















Yii Learning Note Five (core Validator API translation)

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.