Yii2 自定义独立验证

Lia*_*iam 1 php validation yii2

好的,我相信我会有很多自定义验证,所以我决定按照Yii Standalone Validation Doc创建一个独立的验证类。

这个特定的验证器是为了确保填写 company_name 或 name,所以必填。

我在 app\components\validators\BothRequired.php 中创建了这个类

<?php
namespace app\components\validators;
use Yii;
use yii\validators\Validator;

class BothRequired extends Validator
{
    public function validateAttribute($model, $attribute)
    {
       //validation code here
    }
}
Run Code Online (Sandbox Code Playgroud)

这是模型

public function rules()
{
    return [
        ['company_name', BothRequired::className(), 'skipOnEmpty' => false, ],
    ];
}
Run Code Online (Sandbox Code Playgroud)

但是,此验证需要将一些参数传递给此示例中的验证,我需要发送需要检查的第二个属性。我似乎无法弄清楚如何做到这一点,如果我在模型本身中创建验证规则,那么我可以通过,$params但我不知道如何传递给这个独立的类。

另外还要注意的是,如果我可以拥有一个包含所有自定义验证器的类,而不是每个验证器的文件,那对我来说会好得多。

有任何想法吗?

问候

Lia*_*iam 5

好的,

在@gandaliter 的帮助下,我找到了答案

验证器类

namespace app\components\validators;
use Yii;
use yii\validators\Validator;

class BothRequired extends Validator
{
    public $other;
    public function validateAttribute($model, $attribute)
    {
        if (empty($model->$attribute) && empty($model->{$this->other})) {
            $this->addError($model, $attribute, 'Either '.$attribute.' or '.$this->other.' is required!');
            $this->addError($model, $this->other, 'Either '.$attribute.' or '.$this->other.' is required!');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

模型规则

public function rules()
{
    return [
        ['company_name', BothRequired::className(), 'other'=>'contact_name', 'skipOnEmpty' => false, ],
    ];
}
Run Code Online (Sandbox Code Playgroud)

如您所见,在这种情况下,您必须声明要发送的属性$other,然后在代码中使用它作为$this->other

然后我可以验证这两个项目。

我希望这能解决问题

利亚姆

PS 在我提到的另一张纸条上.... 如何将所有验证器放在一个类中?