This example describes the Yii core Validator API. Share to everyone for your reference, specific as follows:
Core Validator Cores validators
Objective
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 the alias required instead of the Yii\validators\requiredvalidator class:
<?php Public
function rules ()
{return
[[
' email ', ' password '], ' required '],
];
>
This yii\validators\validator:: $builtInValidators attribute Life all supported validator aliases.
Next, we will explain the use of each core validator.
1. Boolean error value
<?php
[
//Check whether "selected" is 0 or 1, regardless of the data type
[' Selected ', ' Boolean '],
//check whether "deleted" is a Boolean class Type, can only be true or false
[' Deleted ', ' Boolean ', ' TrueValue ' => true, ' Falsevalue ' => false, ' strict ' => true],
]
?>
The above detection is a bool value.
truevalue: The value that represents true. The default is ' 1 '.
falsevalue: The value that represents false. The default is ' 0 '.
Strict: Whether the value in the input box must match the set of TrueValue and Falsevalue. The default is False.
Note: Because data submissions are Fu Yi in HTML form, you typically need to set the strict property to false.
2. CAPTCHA Verification Code
<?php
[
[' Verificationcode ', ' captcha '],
]
?>
This validator is typically and
Yii\captcha\captchaaction and
Yii\captcha\captcha is used together to ensure that the same verification code is entered through the CAPTCHA component.
casesensitive: Verify that the code needs to be case-sensitive. The default is False.
captchaaction: The default CAPTCHA action of the validation code generates the path of CAPTCHA image. The default is ' Site/captcha '.
skiponempty: Whether or not to skip validation when the input is empty. Default false, that is, input input is required.
3. Compare comparison
<?php
[
//Verify that the "password" attribute and "password_repeat" are equal
[' password ', ' compare '],
//Validate age >= 30
[' age ', ' compare ', ' comparevalue ' =>, ' operator ' => ' >= '],
]
? >
This validator compares the specified input value with 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 compares it with the attribute with the same name but with the suffix _repeat. For example, if the property name to be validated is password, then the default Contrast 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 operator of the comparison. The default is = =, which means that the input value is equal to the Compareattribute or CompareValue value before it succeeds.
The following operators are supported: = =, = = =,!=,!==, >, >=, <, <=.
4. Date Dates
<?php
[[
[' from_date ', ' to_date '], ' date '],
]
?>
This validator checks that the value entered is a date, time, or DateTime in an appropriate form. Optionally, he can convert the input value into a UNIX timestamp stored in a property specified by Timestampattribute.
Format: This date/time is all supported formats 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 the conversion will be entered. It can also be the same property name as was validated. If this is the case, the original value will be overwritten by the timestamp. You can look at "How to handle date selector DatePicker" with examples.
Http://www.yiiframework.com/doc-2.0/widget-jui
If the input is optional, you may also want to add a default value filter in addition to date validation to ensure that null input is stored as null. Otherwise you may end up getting a date like the date selector 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" as "USA" if he is empty
[' Country ', ' Default ', ' Value ' => ' USA '],
//Assign "from" and "to" respectively plus 3 days and 6 days if they are empty words
[[' From ', ' to '], ' defaul T ', ' 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
<?php
function 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 caps, no settings, no checks.
min: Digital offline, no settings not checked
7. Email Email Verification
<?php
[
//Check mailbox is a valid "email" address
[' email ', ' email '],
]
?>
allowname: Check if the name is allowed to appear in the mailbox (e.g. John Smith <john.smith@example.com>). The default is False.
Checkdns, check to see if the e-mail domain name exists, and whether there is any a or MX record. Note that this may check that a temporary DNS problem fails, even if the e-mail address is actually valid. The default is False.
enableidn, the validation process should take into account IDN (internationalized Domain name). The default is False. It is important to note that in order to use IDN authentication you must install and enable the International PHP extension, or the exception will be thrown.
8. Whether exist exists
<?php
[
//A1 need to have "A1" in the property column this seems to be the default.
[' A1 ', ' exist '],
//A1 exist, but its value will use A2 to check for Presence
[' A1 ', ' Exist ', ' Targetattribute ' => ' A2 '],
//A1 and A2 need to exist simultaneously, they will all receive error messages
[[' A1 ', ' A2 '], ' exist ', ' Targetattribute ' =&G T [' A1 ', ' A2 ']],
//A1 and A2 need to exist simultaneously, only A1 will receive error Messages
[' A1 ', ' exist ', ' targetattribute ' => ', ' A1 ', ' A2 ']],
//A1 Needs to exist by detecting A2 and A3 (with A1 value)
[' A1 ', ' exist ', ' targetattribute ' => ', ' A2 ', ' A1 ' => ' A3 ']],
//A1 need to exist. If A1 is a arrays, then 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 and only works in the properties of the Active record model.
He supports verifying single or multiple columns
targetclass: An Active record class name used to look for input value validation. If not set, the currently set model class is used by default.
Targetattribute: The name of the property that should be used to validate the input value in the Targetclass. If not set, the name of the property that is currently being validated is used. You can use arrays to verify the existence of multiple columns. 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 key and the value are the same, you can specify the value.
Filter: Additional filter to is applied to the DB query used to check the existence of the input value. This can is a string or a array representing the additional query condition (refer to Yii\db\query::where () on the format Query condition), or a anonymous function with the signature function ($query), where $query is the query object Can modify in the function.
Allowarray: The value that is allowed to enter is an array. Default false. If the property is true and the input is an array, then each element that is cooked 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 multiple columns by setting Targetattribute to an array.
9. File verification
<?php
[//
check "primaryimage" uploaded file format is PNG, JPG or GIF
///The file size must be less than 1MB
[' primaryi Mage ', ' 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-delimited 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 resources that are allowed to be uploaded. He can be an array or a string (such as. "Image/jpeg, Image/png") separated by commas or spaces. case-insensitive, default is null, which means that all file extensions are allowed.
minsize: The minimum number of bytes to upload file is not set without judgment.
maxSize: The maximum number of bytes uploaded file is not set without judgment.
maxfiles: The maximum number of uploaded files defaults to 1, meaning that only individual files can be uploaded to a single file upload box. If greater than 1, then input must be an array containing up to maxfiles number of uploaded files.
checkextensionbymimetype: 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 this check.
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 filters
<?php
[
///Remove "username" and "email" input spaces skip several group validation
[[' username ', ' email '], ' filter ', ' filter ' => ' trim ', ' SK Iponarray ' => true],
//verify normal "phone" input
[' phone ', ' filter ', ' Filter ' => function ($value) {
//Verify correctness of phone code return
$value;
}],
]
?>
This validator cannot verify the data. Conversely, it applies a filter on the input value and assigns it 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 the <?php function ($value) {return $newValue;} ?> This attribute must be set.
Skiponarray: Skip when the input is just an array. The default is False. Note that if the filter cannot handle array input, you should set this property to True. Otherwise, some PHP errors may occur.
Tips: Go to the blanks directly with the trim verification.
Tip: Partial encapsulation can directly use system functions such as Intval:
<?php
[' property ', ' filter ', ' Filter ' => ' Boolval '],
[' property ', ' filter ', ' Filter ' => ' intval '],
?>
Image Image
<?php
[
//Check "Primaryimage" is a valid picture and size appropriate
[' primaryimage ', ' image ', ' Extensions ' => ' png, jpg ', c10/> ' MinWidth ' =>, ' maxwidth ' => 1000, ' minheight '
=>, ' MaxHeight ' => 1000,
],
]
?>
Extension of File verifier:
minwidth: The minimum width is not unlimited.
maxwidth: Maximum width is not unlimited.
minheight: The minimum height is unlimited.
maxheight: Maximum height does not have unlimited.
The value of the inside of an array
<?php
[
//check "level" is 1, 2 or 3
[' Level ', ' in ', ' Range ' => [1, 2, 3]]],
]
?>
Checks whether the entered value exists in the list of given series values.
Range: A list of the given range values.
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 result should be reversed. The default is False. When this property is set to True, validation checks that the value entered 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 validation will fail.
Verification of Integer integer
<?php
[
//Check "age" is an integer value
[' Age ', ' Integer '],
]
?>
Max: The upper limit is not set without checking.
min: The lower limit does not set not to check.
Match regular Match check
<?php
[
//Check "username" begins with a letter and contains only literal characters
[' username ', ' match ', ' pattern ' => '/^[a-z]\w*$/i ']
]
? >
An input value specifies a regular expression matching validation check.
Pattern: The rules that the input values must match. property must be set, otherwise an exception will be thrown.
not: Reverses the validation results. Default false.
Number check
<?php
[
//Check "salary" is a number
[' salary ', ' numbers '],
]
?>
Equivalent to double validator.
Max: The upper limit is not set without checking.
min: The lower limit is not set without checking.
Required is an empty check
<?php
[
//check "username" and "password" are not empty
[[' Username ', ' password '], ' required '],
]
? >
This validator prevents users from submitting blank form data.
requiredvalue: The value that should be entered. If not set means that the input value should not be empty.
Strict: Whether the data type should be checked when validating a value. Default false. When Requiredvalue is not set, if this property is true, the validator checks that the input value is not strictly null; If you change the property false, the validator will use a loose rule to determine whether a value is empty or not. When Requiredvalue is set, the comparison between input and Requiredvalue also checks the data type, if this property is true.
Safe Mark Input is a security attribute
<?php
[
//Mark "description" is a safe property
[' Description ', ' safe '],
]
?>
This validator does not perform data validation. Instead, it is used to mark the property as a security attribute (I guess the effect is not to do the word escape bar).
String validation
<?php
[
//check "username" is a string and has a length between 4 and 24
[' Username ', ' string ', ' length ' => [4,]],
]
?>
This validator checks that the value entered is a string and that the length is within the range of the definite value.
Length: Specifies the lengths of the strings to be validated. You can specify the following forms:
An integer: The exact length of the string;
Single array element: the minimum length of input (e.g. [8]). Must be more than 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 set without restriction.
Max: The maximum length of the input string is not set without restrictions.
encoding: The encoding for the input string does not have the default UTF-8 set.
Trim to Space
<?php
[
//Remove "username" and "email" on both sides of the space
[[' username ', ' email '], ' trim '],
]
?>
No data validation only go to space if the property is an array, this filter will be automatically ignored.
Unique Uniqueness Validation
<?php
[
//A1 need to be unique [' A1 ', ' Unique '] in the column represented by the "A1" attribute,
//A1 must be unique, but column A2 uniqueness of the A1 value to check for
[' A1 ', ' Unique ', ' Targetattribute ' => ' A2 '], the
needs of//A1 and A2 are unique, and they 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 A1 value) is unique
[' A1 ', ' Unique ', ' targetattribute ' => ', ' A2 ', ' A1 ' => ' A3 ']],
]
?>
This verifies the check if the value entered is the only one in the table column. It applies only to the properties of the active record model. It supports validation of any single column or columns.
Targetclass: Should be the name of the active record class that is used to validate lookup input values. If there is no setting, the class that will be used is currently validating the model.
Targetattribute: The name of the property that should be used to validate the uniqueness of the input value in Targetclass. If not set, the name of the property that is currently being validated is used. You can use arrays to validate the uniqueness of multiple columns. The value of the array is the property that will be used to validate uniqueness, and the array key is the property whose value is to be validated. If the key and the value are the same, you can specify the value.
Filter:a additional filters are applied to database queries that check the uniqueness of the input values. This can be a string or an array that represents an additional query condition (the format of the reference Yii\db\query::where () query condition), or an anonymous function like: function ($query), where $query is a function that you can modify in the query object.
Http://www.yiiframework.com/doc-2.0/yii-db-query.html
URL address Verification
<?php
[//
Check ' website ' is a valid URL. Front "http://" to "website" attribute
//If it does not have a URI pattern
[' website ', ' URL ', ' de Faultscheme ' => ' http '],
]
?>
validschemes: An array specifies that the URI scheme should be considered valid. The default is [' HTTP ', ' HTTPS '], meaning that HTTP and HTTPS URLs are considered valid.
defaultscheme: The default URI scheme is to anticipate input if it does not have a part of the scenario. The default is null, which means that the input value is not modified.
enableidn: Verify that IDN (internationalized Domain name) should be considered. The default is False. It is important to note that in order to use IDN authentication you must install and enable the International PHP extension, otherwise the exception will be thrown.
For more information on YII-related content, readers who are interested in this site can view the topics: Introduction to YII Framework and summary of common skills, "Summary of PHP Excellent development framework", "Smarty Template Introductory Course", "Introduction to PHP object-oriented programming", "PHP string" Summary of Usage , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"
I hope this article will help you with the PHP program design based on the YII framework.