美文网首页
yii2 form表单 rules()

yii2 form表单 rules()

作者: 出门遇到猪 | 来源:发表于2019-06-09 13:08 被阅读0次

https://www.yiichina.com/doc/api/2.0/yii-base-model#rules()-detail

entryForm页面  rules()方法

Returns the validation rules for attributes

返回属性的验证规则。

Each rule is an array with the following structure

每个规则都是具有以下结构的数组

[

    ['attribute1', 'attribute2'],                     属性名称

    'validator type',                                   验证器类型

    'on' => ['scenario1', 'scenario2'],        应用验证规则的函数数组

    //...other parameters...                       其他参数

]

属性列表:必选项,指定要验证的属性数组,对于单个属性,可以传递一个字符串;

验证程序类型:必需,指定要使用的验证程序。它可以是内置的验证程序名称、模型类的方法名称、匿名函数或验证程序类名。

on:可选,指定可在其中应用验证规则的函数数组。如果未设置此选项,则规则将应用于所有函数。

可以指定其他名称-值对来初始化相应的验证器属性。有关可能的属性,请参考单个验证器类API。

验证程序可以是扩展yii\validators\validator的类的对象,也可以是具有以下签名的模型类方法(称为内联验证程序):

// $params refers to validation parameters given in the rule

function validatorName($attribute, $params)

在上面,$attribute指的是当前正在验证的属性,而$params包含一个验证器配置选项数组,例如字符串验证器的max。当前正在验证的属性的值可以访问为$this->$attribute。注意$before属性;这是以变量$attribute的值作为要访问的属性的名称。

yii还提供了一组内置验证器。每个别名都可以在指定验证规则时使用。

以下是一些例子:

[

    // built-in "required" validator    [['username', 'password'], 'required'],

    // built-in "string" validator customized with "min" and "max" properties    ['username', 'string', 'min' => 3, 'max' => 12],

    // built-in "compare" validator that is used in "register" scenario only    ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],

    // an inline validator defined via the "authenticate()" method in the model class    ['password', 'authenticate', 'on' => 'login'],

    // a validator of class "DateRangeValidator"    ['dateRange', 'DateRangeValidator'],

];

注意,为了继承在父类中定义的规则,子类需要使用array_merge()等函数将父规则与子规则合并。

相关文章

网友评论

      本文标题:yii2 form表单 rules()

      本文链接:https://www.haomeiwen.com/subject/pjogxctx.html