kop / yii2-conditional-validator
Yii2 框架的条件验证规则
Requires
- php: >=5.4.0
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2019-10-10 10:02:14 UTC
README
注意:自版本
2.0.0-beta
以来,Yii2 内置了条件验证器,集成到核心中。请使用框架提供的验证器。此扩展将不再接收更新。
Yii2 Conditional Validator (Y2CV) 根据某些条件(规则)验证一些属性。您可以使用任何核心验证器,就像您通常所做的那样,或者任何其他基于类或内联验证器。一个有趣的功能是,您甚至可以在 Y2CV 内部使用自己的 Y2CV 来执行更复杂的条件。基本上,Y2CV 执行在 if
参数中设置的规则,如果没有错误,则执行在 then
参数中设置的规则。
需求
- Yii 2.0
- PHP 5.4
安装
安装此扩展的最佳方式是通过 Composer。
运行以下命令之一:
php composer.phar require kop/yii2-conditional-validator "dev-master"
或者将以下内容添加到您的 composer.json
文件的 require
部分:
"kop/yii2-conditional-validator": "dev-master"
语法示例
[['safeAttributes'], `path.to.ConditionalValidator`, 'if' => [ // rule1: [['attrX', 'attrY'], 'required', ... ] // ruleN: ... ], 'then' => [ // rule1: [['attrZ', 'attrG'], 'required', ... ] // ruleN: ... ] ]
safeAttributes
:应转换为安全的属性的名称(因为 Yii 没有方法使动态验证器使属性安全);path.to.ConditionalValidator
:在大多数情况下将是ConditionalValidator::className()
;if
:(二维数组)要验证的条件规则。只有当它们全部有效(即,没有错误)时,才会验证then
参数中的规则;then
:(二维数组)只有当if
参数中的规则没有错误时,才会验证的规则。
注意:在
if
参数中设置的规则中的错误在检查后将被丢弃。只有then
参数中设置的规则中的错误才会真正保留。
使用示例
如果
customer_type 是 "active" 则
birthdate 和 city 是必需的
public function rules() { return [ [['customer_type'], ConditionalValidator::className(), 'if' => [ [['customer_type'], 'compare', 'compareValue' => 'active'] ], 'then' => [ [['birthdate', 'city'], 'required'] ] ] ]; }
如果
customer_type 是 "inactive" 则
birthdate 和 city 是必需的 并且 city 必须是 "sao_paulo","sumare" 或 "jacarezinho"
public function rules() { return [ [['customer_type'], ConditionalValidator::className(), 'if' => [ [['customer_type'], 'compare', 'compareValue' => 'active'] ), 'then' => [ [['birthdate', 'city'], 'required'], [['city'], 'in', 'range' => ['sao_paulo', 'sumare', 'jacarezinho']] ] ] ]; }
如果
information 以 'http://' 开头 并且 至少有 24 个字符长度 则
自身的 information 必须是有效的 URL
public function rules() { return [ [['information'], ConditionalValidator::className(), 'if' => [ [['information'], 'match', 'pattern' => '/^http:\/\//'], [['information'], 'string', 'min' => 24, 'allowEmpty' => false] ), 'then' => [ [['information'], 'url'] ] ] ]; }
许可证
yii2-conditional-validator 在 MIT 许可证下发布。有关详细信息,请参阅附带文件 LICENSE.md
。