YII2 Framework Data validation Operation example detailed

Source: Internet
Author: User
This article mainly introduced the YII2 framework data validation operation, combined with the case form detailed analysis the YII framework common data validation operation principle, the realization method and the related operation skill, the need friend can refer to the next

The examples in this paper describe the YII2 framework data validation operation. Share to everyone for your reference, as follows:

First, the scene

What circumstances do you need to use the scene? When a model needs to be used in a different context, it is necessary to define multiple scenarios to differentiate between different usage scenarios if the data table fields and data validation rules required in different contexts differ. For example, when users sign up for an email, they don't need to log in, and you need to define two different scenarios to differentiate them.

By default, the scenario for the model is determined by the rules() scenario used in the validation rules for the method declaration, or you can scenarios() define all the scenarios of the model more specifically by overriding the method, for example:

Public function Scenarios () {    return [      ' signup ' = ' = ' username ', ' email ', ' password ', ' Conpassword ', ' Verifycode ', ' reg_time ', ' log_time '],      ' login ' = [' username ', ' password ', ' Verifycode ', ' rememberme ', ' Log_ ' Time ']    ];}

Where the key is the scene name, the value is the Model property (called the Activity property) used in the scene.

There are two ways to specify the model scenario:

Method One:

$model = new User (); $model->scenario = ' signup ';

Method Two:

$model = new User ([' Scenario ' = ' signup ']);

You can declare a scenario where a validation rule applies by specifying the ' on ' property in the validation rule:

[' email ', ' required ', ' on ' = ' signup ']

Scenarios are primarily used for model attribute block assignment and data validation. When you call a method of a model class for a load() block assignment, only the attributes used by the current scene are assigned, and when the method of the model class is called for validate() data validation, only the validation rules that are relevant to the current scene properties and that apply to the current scene are executed.

Ii. validation Rules

The YII model class declares all the validation rules used by implementing the Rules () method, as an example:

Public Function Rules () {    return [[      ' username ', ' password '], ' required '],      [' email ', ' e-mail ', ' on ' = ' Signup ']    ;}

A rule can be applied to one or more scenarios, a rule that validates one or more properties, and one property can correspond to one or more validation rules. If the ' on ' attribute is not specified, the validation rule is used in all scenarios.

All validation rules can customize the error message by setting the ' message ' property, and the current property tag name (the property tag name needs to be set in the model's Attributelabels () method) through {attribute} in the error message content. Value} To reference the input value of the current property, for example:

[' username ', ' unique ', ' on ' + ' register ', ' message ' = ' {attribute} ' ' {value} ' has been occupied! ' On ' + ' signup ']//the user name is unique when registering

Yii authentication is used in the following three ways:

1. Client Authentication:

Yii turns on client-side validation by default, and can be turned on by setting the Enableclientvalidation parameter to True, and then ActiveForm reads the validation rules declared in the model to generate the appropriate JavaScript validation code. There are three ways to set the Enableclientvalidation parameter:

(1) Set the entire form in the view file ActiveForm:

<?php$form = Activeform::begin ([  ' enableclientvalidation ' =>true]);? >

(2) Set the individual field in the View file Activefield:

Copy the Code code as follows:

<?= $form->field ($model, ' username ', [' enableclientvalidation ' =>false])->label (' username ')?>

(3) Set in the Rules () function of the AR class:
[' username ', ' yii\validators\stringvalidator ', ' min ' = 3, ' max ' = ', ' enableclientvalidation ' = true, ' on ' =& Gt ' Register ']

Priority: (2) > (1) > (3)

2. Server-side validation:

(1) Validate ()

The model validate() method validates all data against the validation rules defined in the rules () method, verifies that the error is saved in the yii\base\model::errors property by returning True, and returns false.

(2) Save ()

The save() method is called by default in the Model method validate() to verify the data, verify that the database operation is performed directly, return true, otherwise do not perform the database operation, return FALSE, store the error information in the Yii\base\model::errors property. If you have explicitly called validate (), you can avoid repeating the validation data in the Save () method by using the Pass parameter: Save (false).

3. Ajax Validation:

Yii turns off Ajax validation by default, which can be enabled by configuring the Enableajaxvalidation parameter to True.

Client settings (two ways):

(1) Set the entire form in the view file ActiveForm:

<?php$form = Activeform::begin ([  ' enableajaxvalidation ' =>true]);? >

(2) Set the individual field in the View file Activefield:

Copy the Code code as follows:

<?= $form->field ($model, ' username ', [' enableajaxvalidation ' =>false])->label (' username ')?>

Priority: (2) > (1)

Server-side processing:

if (Yii:: $app->request->isajax) {    $res = \yii\bootstrap\activeform::validate ($model);    Yii:: $app->response->format = \yii\web\response::format_json;    return $res;}

Note: Some validation rules cannot use client-side validation, such as: unique, exist, and so on.

Third, Yii Core validator

Yii provides some core validators that can be used directly, stating the following format:

[' Property name ', ' Authenticator name/class name ', ... (some additional parameter settings)]

Understanding and using Yii's core validator can make development much easier. The following is a simple introduction to the Yii Core validator classification.

1. validators that do not perform data validation

(1) Safe: Instead, mark a property as a security attribute.

[' desc ', ' safe ']

(2) Default: Sets defaults for properties with null values.

[' Add_time ', ' Default ', ' value ' = time ()]

(3) Trim: Remove excess space between the ends of the input value.

[' username ', ' trim ']

(4) Filter: Filter, the data is formatted or some other processing after the return.

[' Phone ', ' filter ', ' filter ' = = function ($value) {
... return $value;
}]

Filter: A PHP callback function that defines a filter, which can be a global function name, an anonymous function, or something else.
Skiponarray: If the filter mirror is skipped when entering an array, the default is False. If the filter cannot handle array input, it should be set to true.

2. Data Type Validator

(1) Boolean: Boolean.

[' Del ', ' Boolean ', ' truevalue ' = ' = ', ' falsevalue ' = False, ' strict ' = true]

TrueValue: Represents the True value, which defaults to 1.
Falsevalue: Represents the False value, which defaults to 0.
Strict: Whether the input data is required to match truevalue or falsevalue strictly. The default is False.

(2) Number: Digital.

[' Salary ', ' number ']

(3) Double: dual-precision floating-point, equivalent to the number validator.

[' Salary ', ' Double ', ' max ' = 99.99, ' min ' = 0]

(4) Integer: Integer.

[' Age ', ' integer ']

Note: The number, double, and integer validators can set the min, max parameters to limit the maximum and minimum values (with bounded points) of the numbers.

(5) String: String.

[' username ', ' string ', ' length ' = [3, 30]]

Length: Specifies the limit of the lengths of the input strings.
Min: The minimum length of the string.
Max: string maximum length.
Encoding: The encoding of the string, not set uses the value of the CharSet property of the application itself. The default is Utf-8.

3. Data Format Validator

(1) Date: day.

[' Time ', ' Date ', ' format ' = ' php:y:m:d ', ' timestampattribute ' = ' startTime ']

Format: Time formats, default to "y-m-d".
Timestampattribute: Converts a time into a timestamp and assigns a value to a property.

(2) Email: Verify that the email address format is met.

[' emailaddr ', ' email ']

(3) IP: Verify that it is a valid IP address.

[' IP_Address ', ' IP ']

(4) URL: URL.

[' website ', ' url ', ' defaultscheme ' = ' http ']

Validschemes: Used to specify which URI schemes are considered valid, default to [' http ', ' HTTPS '].
Defaultscheme: If the input value does not have a corresponding scheme prefix, the default URI scheme prefix is used.

(5) Match: The input value satisfies a regular expression.

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

Pattern: Regular expression.
Not: Negates the validation result.

4. Data Value Validator

(1) Required: required.

[[' Username ', ' password '], ' required ']

Requiredvalue: The expected value, if not set, the input cannot be empty.
Strict: Checks whether the type is checked when the value is entered.

(2) CAPTCHA: Verification code.

[' Verifycode ', ' captcha ', ' casesensitive ' = True, ' captchaaction ' = ' site/captcha ', ' skiponempty ' = false]

CaseSensitive: Is case sensitive, the default is False.
Captchaaction: Route to the Captcha method used to render the Authenticode picture, default to ' Site/captcha '.
Skiponempty: Whether to skip validation when the input is empty, and false by default.

(3) Compare: comparison.

[' Password ', ' compare ', ' compareattribute ' = ' conpassword ', ' operator ' = ' = = ']

Compareattribute: The name of the property compared to the specified property value.
CompareValue: Compared to a constant value.
Operator: comparison operator.

where Compareattribute defaults to the validation property with the suffix "_repeat" as the name of another comparison property, operator defaults to "= =", i.e.: [' password ', ' compare '] The rule indicates whether the values of password and password_repeat are equal.

(4) Each: validates the array.

[' IDs ', ' each ', ' rule ' = = [' Integer ']]

(Verify that each element in the array IDs is of type int data)
Rule: Defines the validation rules that validate each array of elements.
Allowmessagefromrule: Whether to use multiple validation rules specified in rule error message, the default is true, if set to false, use the "message" parameter value as the error message.

Note: If the input value is not an array, an error will be added .

(5) Exist: existence.

[' CID ', ' exist ', ' targetclass ' = ' app\models\category ', ' targetattribute ' + ' ID ']

(The value of the CID exists in the id attribute of the AR class, usage scenario: The CID field of the data table associated with the current AR model is associated with the ID field of the data table associated with the category model, so use this validation rule to verify that the value of the CID field can find the corresponding record in another associated datasheet)
Targetclass: The target AR class used to find the input value.
Targetattribute: The name of the target attribute used to find the input value.
Filter: Checking the existence of attribute values requires a database query, which sets the filter criteria for the query. You can set a string or array of criteria for a query, or function ($query) anonymous functions.
Allowarray: If the input value is allowed to be an array, the default is False. If set to True, each element of the array must exist in the Target field. This property cannot be set to True if the Targetattribute is set to a multivariate prime group to verify the presence of the measured value in multiple fields.

(6) Unique: Uniqueness.

[' email ', ' unique ', ' targetclass ' = ' app\models\user ', ' message ' + ' {attribute} ' {value} ' has been registered! ' On ' = ' signup ']
In addition to the Allowarray property, the other properties are the same as the exist validator.

(7) in: Range.

[' Sex ', ' in ', ' range ' = [0, 1, 2]

Range: A list of range values.
Strict: Whether to use strict mode (the same type as the value).
Not: The default is False if the result of validation is reversed.
Allowarray: Whether to accept input array, default is False.

5. File verifier

(1) File: Files.

[' pcimg ', ' file ', ' extensions ' = [' png ', ' jpg ', ' gif '], ' maxSize ' and 1024*1024]

Extensions: List of file extensions that can be accepted for uploading.
Mimetypes: A list of MIME types that can be accepted for uploading.
MinSize: Minimum file size.
MaxSize: Maximum file size.
Maxfiles: Maximum number of uploaded files, default is 1. The input value that is set to greater than 1 o'clock must be an array.
Checkextensionbymimetype: Whether the file extension is judged by the MIME type of the file, which is true by default.

(2) Image: Image.

[' mbimg ', ' image ' extensions = ' png, IPG ', ' minWidth ' and ' = ', ' minheight ' + 100]

The validator inherits from the file validator and supports additional properties MinWidth, MaxWidth, MinHeight, maxheight to set the minimum, maximum width, and minimum and maximum height of the picture.

Iv. other validators

1. Conditional Validation:

[' state ', ' required ', ' when ' = function ($model) {///only when the country property value is ' USA ', the State property value cannot be empty     return $model- country== ' USA ';}]

Note: If you need to support client-side validation, configure the ' Whenclient ' property.

1. Custom Validator:

(1) Inline validator: A validator that is defined in the form of a model method or an anonymous function.

Example:

[' Conpassword ', function ($attribute, $params) {     if ($this, $attribute! = $this->newpassword) {        $this- >adderror ($attribute, ' Confirm password and new password are inconsistent! ');    }}].

(The Yii core Validator ' compare ' can also be used here)

Note: The inline validator does not support client-side validation.

(2) Independent authenticator:

A standalone validator is a class that inherits from Yii\validators\validator or its subclasses, and can be overridden validateAttribute() to implement validation rules, and if validation fails, the method can be called to yii\base\Model::addError() hold the error message inside the model.

Standalone Validator Example:

Namespace App\components;use Yii\validators\validator;class Conpasswordvalidator extends Validator {public     function init () {         parent::init ();         $this->message = ' Confirm password and password are inconsistent! ';     }     Server-side validation public     function ValidateAttribute ($model, $attribute) {         if ($model->conpassword!== $model Password) {              $model->adderror ($attribute, $this->message);         }     }     Client-side validation public     function Clientvalidateattribute ($model, $attribute, $view) {         $conpassword = Json_encode ($ Model->conpassword);         $message = Json_encode ($this->message, json_unescaped_slashes | Json_unescaped_unicode);     Return <<<jsif (Value! = $conpassword) {     message.push ($message);} JS;         return false;     }}

Examples used in models:

[' Conpassword ', ' app\components\conpasswordvalidator ']

Finally, it is important to note that the order in which the validation rules are declared has an impact on the validation results!

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.