Detailed explanation on the use of Yii2 framework data verification

php中世界最好的语言
Release: 2023-03-25 21:20:02
Original
2179 people have browsed it

This time I will bring you a detailed explanation of the use of Yii2 framework data verification. What are the precautions for using Yii2 framework data verification? The following is a practical case, let's take a look.

1. Scenario

Under what circumstances do we need to use scenarios? When a model needs to be used in different scenarios, if the data table fields and data validation rules required in different scenarios are different, multiple scenarios need to be defined to distinguish different usage scenarios. For example, users need to fill in their email when registering, but not when logging in. In this case, two different scenarios need to be defined to distinguish them.

By default, the scenario of the model is determined by the scenario used in the verification rules declared by the rules() method. It can also be overridden by the scenarios() method. to more specifically define all scenarios of the model, for example:

public function scenarios() {
    return [
      'signup' => ['username', 'email', 'password', 'conpassword', 'verifyCode', 'reg_time', 'log_time'],
      'login' => ['username', 'password', 'verifyCode', 'rememberMe', 'log_time']
    ];
}
Copy after login

where the key is the scenario name and the value is the model attribute used in the scenario (called the activity attribute).

There are two ways to specify the model scene:

Method one:

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

Method two:

$model = new User(['scenario' => 'signup']);
Copy after login

You can declare the applicable scenario of a validation rule by specifying the 'on' attribute in the validation rule:

['email', 'required', 'on' => 'signup']
Copy after login

The scenario is mainly used for model attribute block assignment and data verification. When calling the load() method of the model class for block assignment, only the attributes corresponding to the current scene will be assigned. When calling the validate() method of the model class for data verification , only the validation rules related to the current scene attributes and applicable to the current scene will be executed.

2. Verification rules

The Yii model class declares all the verification rules used by implementing the rules() method, example:

public function rules() {
    return [
      [['username', 'password'], 'required'],
      ['email', 'email', 'on' => 'signup']
    ];
}
Copy after login

A rule can be applied to one or more scenarios, a rule can be used to verify one or more attributes, and an attribute can correspond to one or more verification rules. If the 'on' attribute is not specified, the validation rule will be used in all scenarios.

All validation rules can customize the error message by setting the 'message' attribute, and the current attribute label name can be referenced through {attribute} in the error message content (the attribute label name needs to be in the model's attributeLabels( ) method setting), refer to the input value of the current attribute through {value}, for example:

['username', 'unique', 'on' => 'register', 'message' => '{attribute}"{value}" is already occupied! ', 'on' => 'signup']//The username is unique when registering

There are three ways to use yii verification:

1. Customer Side-side verification:

Yii turns on client-side verification by default. You can turn it on by setting the enableClientValidation parameter to true. After turning it on, ActiveForm will read the verification rules declared in the model and generate the corresponding Javascript verification code. There are three ways to set enableClientValidation parameters:

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

<?php
$form = ActiveForm::begin([
  &#39;enableClientValidation&#39; =>true
]);
?>
Copy after login

(2) Set a single field in the view file ActiveField:

<?= $form->field($model, &#39;username&#39;, [&#39;enableClientValidation&#39;=>false])->label(&#39;用户名&#39;) ?>
Copy after login

(3) Set in the rules() function of the AR class:

[&#39;username&#39;, &#39;yii\validators\StringValidator&#39;, &#39;min&#39; => 3, &#39;max&#39; => 30, &#39;enableClientValidation&#39; => true, &#39;on&#39; => &#39;register&#39;]
Copy after login

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

2. Server-side verification:

(1) validate()

Modelvalidate() method will Validate all data according to the validation rules defined in the rules() method. If the validation passes, true will be returned. Otherwise, errors will be saved in the yii\base\Model::errors attribute and false will be returned.

(2)save()

Modelsave()The validate() method is called by default for data verification. If the verification passes, it will be directly Perform database operation and return true. Otherwise, no database operation will be performed and false will be returned. The error information will be stored in the yii\base\Model::errors attribute. If validate() has been explicitly called, you can avoid repeatedly validating the data in the save() method by passing parameters: save(false).

3. Ajax verification:

Yii turns off ajax verification by default and can be turned on by configuring the enableAjaxValidation parameter to true.

客户端设置(两种方式):

(1)在视图文件ActiveForm中对整个form进行设置:

<?php
$form = ActiveForm::begin([
  &#39;enableAjaxValidation&#39; =>true
]);
?>
Copy after login

(2)在视图文件ActiveField中对单个field进行设置:

<?= $form->field($model, &#39;username&#39;, [&#39;enableAjaxValidation&#39;=>false])->label(&#39;用户名&#39;) ?>
Copy after login

优先级:(2)>(1)

服务器端处理:

if(Yii::$app->request->isAjax) {
    $res = \yii\bootstrap\ActiveForm::validate($model);
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return $res;
}
Copy after login

注:有些验证规则无法使用客户端验证,如:unique、exist等。

三、yii核心验证器

Yii提供了一些核心验证器,可以直接使用,申明格式如下:

['属性名', '验证器名称/类名', ...(一些额外参数设置)]

了解并使用yii的核心验证器会让开发变得简单许多。下面简单对yii核心验证器进行分类介绍。

1. 不进行数据验证的验证器

(1)safe:而是把一个属性标记为安全属性。

[&#39;desc&#39;, &#39;safe&#39;]
Copy after login

(2)default:给值为空的属性设置默认值。

[&#39;add_time&#39;, &#39;default&#39;, &#39;value&#39; => time()]
Copy after login

(3)trim:去除输入值首尾两侧多余空格。

[&#39;username&#39;, &#39;trim&#39;]
Copy after login

(4)filter:滤镜,对数据进行格式化或一些其他处理后返回。

[&#39;phone&#39;, &#39;filter&#39;, &#39;filter&#39; => function($value) {
         ....return $value;
}]
Copy after login

filter: 用于定义滤镜的php回调函数,可以为全局函数名,匿名函数或其他。
skipOnArray:是否在输入为数组时跳过滤镜,默认为false。如果滤镜不能处理数组输入,应该设置为true。

2. 数据类型验证器

(1)boolean:布尔型。

[&#39;del&#39;, &#39;boolean&#39;, &#39;trueValue&#39; => true, &#39;falseValue&#39; => false, &#39;strict&#39; => true]
Copy after login

trueValue:代表真的值,默认为1。
falseValue:代表假的值,默认为0。
strict:是否要求输入数据必须严格匹配trueValue或falseValue。默认为false。

(2)number:数字。

[&#39;salary&#39;, &#39;number&#39;]
Copy after login

(3)double:双精度浮点型,等效于number验证器。

[&#39;salary&#39;,&#39;double&#39;, &#39;max&#39; => 99.99, &#39;min&#39; => 0]
Copy after login

(4)integer:整数。

[&#39;age&#39;, &#39;integer&#39;]
Copy after login

注:number、double、integer验证器都可以设置min、max参数来限制数字的最大、最小值(含界点)。

(5)string:字符串。

[&#39;username&#39;, &#39;string&#39;, &#39;length&#39; => [3, 30]]
Copy after login

length:指定输入字符串的长度限制。
min:字符串最小长度。
max:字符串最大长度。
encoding:字符串的编码方式,不设置则使用应用自身的charset属性值。默认为utf-8。

3. 数据格式验证器

(1)date:日期。

[&#39;time&#39;, &#39;date&#39;, &#39;format&#39; => &#39;php:Y:m:d&#39;, &#39;timestampAttribute&#39; => &#39;startTime&#39;]
Copy after login

format:时间格式,默认为“y-m-d”。
timestampAttribute:将时间转化为时间戳并赋值给某个属性。

(2)email:验证是否符合邮箱地址格式。

[&#39;emailAddr&#39;, &#39;email&#39;]
Copy after login

(3)ip:验证是否为有效IP地址。

[&#39;ip_address&#39;, &#39;ip&#39;]
Copy after login

(4)url:网址。

[&#39;website&#39;, &#39;url&#39;, &#39;defaultScheme&#39; => &#39;http&#39;]
Copy after login

validSchemes:用于指定哪些URI方案会被视为有效,默认为['http', 'https']。
defaultScheme:若输入值没有对应的方案前缀,会使用的默认URI方案前缀。

(5)match:输入值是否满足某个正则表达式

[&#39;username&#39;, &#39;match&#39;, &#39;pattern&#39; => &#39;/^[a-z]\w*$/i&#39;]
Copy after login

pattern:正则表达式。
not:是否对验证结果取反。

4. 数据值验证器

(1)required:必填。

[[&#39;username&#39;, &#39;password&#39;], &#39;required&#39;]
Copy after login

requiredValue:所期望的值,若没设置则输入不能为空。
strict:检查输入值时是否检查类型。

(2)captcha:验证码。

[&#39;verifyCode&#39;, &#39;captcha&#39;, &#39;caseSensitive&#39; => true, &#39;captchaAction&#39; => &#39;site/captcha&#39;, &#39;skipOnEmpty&#39; => false]
Copy after login

caseSensitive:是否大小写敏感,默认为false。
captchaAction:指向用于渲染验证码图片的captcha方法的路由,默认为'site/captcha'。
skipOnEmpty:输入为空时是否跳过验证,默认为false。

(3)compare:比较。

[&#39;password&#39;, &#39;compare&#39;, &#39;compareAttribute&#39; => &#39;conpassword&#39;, &#39;operator&#39; => &#39;==&#39;]
Copy after login

compareAttribute:与指定属性值比较的属性名称。
compareValue:与某个常量值比较。
operator:比较操作符。

其中compareAttribute默认在验证属性后面加后缀“_repeat”作为另一个比较属性的名称,operator默认为“==”,即:['password', 'compare']规则表示验证password与password_repeat的值是否相等。

(4)each:验证数组。

[&#39;ids&#39;, &#39;each&#39;, &#39;rule&#39; => [&#39;integer&#39;]]
Copy after login

(验证数组ids中的每个元素是否都是int类型数据)
rule:定义验证每一个数组元素的验证规则。
allowMessageFromRule:是否使用rule中指定的多个验证规则报错信息,默认为true,若设置为false,则使用“message”参数值作为错误信息。

注:若输入值不是数组则会报错

(5)exist:存在性。

[&#39;cid&#39;, &#39;exist&#39;, &#39;targetClass&#39; => &#39;app\models\Category&#39;, &#39;targetAttribute&#39; => &#39;id&#39;]
Copy after login

(cid的值是否在AR类对应的id属性中存在,使用场景:当前AR模型关联的数据表的cid字段和Category模型关联的数据表的id字段相关联,所以使用该验证规则验证cid字段的值能否在关联的另一个数据表中找到对应记录)
targetClass:用于查找输入值的目标AR类。
targetAttribute:用于查找输入值的目标属性名称。
filter:检查属性值存在性需要进行数据库查询,该参数设置查询的过滤条件。可以设置为查询条件的字符串或数组,或者function($query)匿名函数。
allowArray:是否允许输入值为数组,默认为false。若设置为true,则数组的每个元素都必须在目标字段中存在。若把targetAttribute设置为多元素数组来验证被测值在多字段中的存在性时,该属性不能设置为true。

(6)unique:唯一性。

[&#39;email&#39;, &#39;unique&#39;, &#39;targetClass&#39; => &#39;app\models\User&#39;, &#39;message&#39; => &#39;{attribute}"{value}"已被注册!&#39;, &#39;on&#39; => &#39;signup&#39;]
Copy after login

除了没有allowArray属性,其他属性都和exist验证器一样。

(7)in:范围。

[&#39;sex&#39;, &#39;in&#39;, &#39;range&#39; => [0, 1, 2]]
Copy after login

range:范围值列表。
strict:是否使用严格模式(类型与值都要相同)。
not:是否对验证的结果取反,默认为false。
allowArray:是否接受输入数组,默认为false。

5. 文件验证器

(1)file:文件。

[&#39;pcImg&#39;, &#39;file&#39;, &#39;extensions&#39; => [&#39;png&#39;, &#39;jpg&#39;, &#39;gif&#39;], &#39;maxSize&#39; => 1024*1024]
Copy after login

extensions:可接受上传的文件扩展名列表。
mimeTypes:可接受上传的MIME类型列表。
minSize:文件大小下限。
maxSize:文件大小上限。
maxFiles:上传文件个数上限,默认为1。设置为大于1时输入值必须为数组。
checkExtensionByMimeType:是否通过文件的MIME类型来判断文件扩展,默认为true。

(2)image:图片。

[&#39;mbImg&#39;, &#39;image&#39; extensions => &#39;png, ipg&#39;, &#39;minWidth&#39; => 100, &#39;minHeight&#39; => 100]
Copy after login

该验证器继承自file验证器,并支持额外属性minWidth、maxWidth、minHeight、maxHeight来设置图片的最小、最大宽度和最小、最大高度。

四、其他验证器

1. 条件式验证:

[&#39;state&#39;, &#39;required&#39;, &#39;when&#39; => function($model) {//只在country属性值为&#39;USA&#39;的时候state属性值才不能为空
     return $model->country==&#39;USA&#39;;
}]
Copy after login

注:若需要支持客户端验证,则要配置'whenClient'属性。

1. 自定义验证器:

(1)行内验证器:一种以模型方法或匿名函数的形式定义的验证器。

示例:

[&#39;conpassword&#39;, function($attribute, $params) {
     if($this->$attribute != $this->newpassword) {
        $this->addError($attribute, &#39;确认密码和新密码不一致!&#39;);
    }
}]。
Copy after login

(当然这里也可以使用yii核心验证器'compare'来实现)

注:行内验证器不支持客户端验证。

(2)独立验证器:

独立验证器是继承自yii\validators\Validator或其子类的类,可以通过重写validateAttribute()方法来实现验证规则,若验证失败,可以调用yii\base\Model::addError()方法来保存错误信息到模型内。

独立验证器示例:

namespace app\components;
use yii\validators\Validator;
class ConpasswordValidator extends Validator {
     public function init() {
         parent::init();
         $this->message = &#39;确认密码和密码不一致!&#39;;
     }
     //服务器端验证
     public function validateAttribute($model, $attribute) {
         if($model->conpassword !== $model->password) {
              $model->addError($attribute, $this->message);
         }
     }
     //客户端验证
     public function clientValidateAttribute($model, $attribute, $view) {
         $conpassword = json_encode($model->conpassword);
         $message = json_encode($this->message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
     return <<<JS
if(value != $conpassword) {
     message.push($message);
}
JS;
         return false;
     }
}
Copy after login

模型中使用示例:

[&#39;conpassword&#39;, &#39;app\components\ConpasswordValidator&#39;]
Copy after login

最后要注意,验证规则申明的先后顺序对验证结果也是有影响的!

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

php使用curl仿制ip与refer步骤详解

php curl batch processing to achieve controllable concurrent asynchronous operation case details

The above is the detailed content of Detailed explanation on the use of Yii2 framework data verification. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template