codeonyii/yii2-at-least-validator

验证至少一个(或多个)属性。

安装量: 200,534

依赖: 1

建议: 0

安全: 0

星标: 28

关注者: 6

分支: 19

开放问题: 8

类型:yii2-extension

v1.2.6 2018-08-24 20:46 UTC

README

Latest Stable Version Total Downloads Build Status Scrutinizer Code Quality CodeFactor

有时,在一组字段中,您需要至少填写其中之一(有时两个或更多)。例如,电话 OR 电子邮件,(facebook OR linkedin) OR (linkedin OR instagram) 等等。您可以使用带有一系列条件规则的 required 验证器来完成此操作。或者,您可以使用 AtLeastValidator。

安装

使用 composer

    composer require "codeonyii/yii2-at-least-validator"

在您的模型中导入验证器

use codeonyii\yii2validators\AtLeastValidator;

class MyModel extends Model
{
...
    public function rules()
    {
        // see examples below
    }
...

示例

在以下示例中,将验证 phoneemail 属性。如果它们都没有填写,则 phone 将收到错误。请注意,in 参数始终是必需的。

     // in rules()
     return [
         ['phone', AtLeastValidator::className(), 'in' => ['phone', 'email']],
     ];

在这里,将验证 facebooklinkedininstagram 属性。如果至少有 2 个(注意 min 参数)未填写,则 facebookinstagram 将收到错误

     // in rules()
     return [
         [['facebook', 'instagram'], AtLeastValidator::className(), 'in' => ['facebook', 'linkedin', 'instagram'], 'min' => 2],
     ];

在摘要中显示错误

如果您想将错误显示在摘要中而不是在各自的属性中,可以这样做

请注意,摘要 不会 在客户端验证中工作。如果您想使用它,应禁用您字段或整个表单的客户端验证。

     // in the rules()
     // please note the exclamation mark. It will avoid the pk attribute to be massively assigned.
     return [
         ['!id', AtLeastValidator::className(), 'in' => ['attr1', 'attr2', 'attr3']], // where `id` is the pk
     ];

     // in the view, show all errors in the summary:
     ...
     echo yii\helpers\Html::errorSummary($model, ['class' => ['text-danger']]);

     // OR, to show only `id` errors:
     echo yii\helpers\Html::error($model, 'id', ['class' => ['text-danger']]);

更新日志

请访问 发布 以查看带有一些描述的版本。