Php Yii2自定义独立验证
好的,我相信我会有很多自定义验证,所以我决定按照创建一个独立的验证类 这个特殊的验证器是为了确保填写了公司名称或名称,所以这两个都是必需的 我已经在app\components\validators\BothRequired.php中创建了这个类Php Yii2自定义独立验证,php,validation,yii2,Php,Validation,Yii2,好的,我相信我会有很多自定义验证,所以我决定按照创建一个独立的验证类 这个特殊的验证器是为了确保填写了公司名称或名称,所以这两个都是必需的 我已经在app\components\validators\BothRequired.php中创建了这个类 <?php namespace app\components\validators; use Yii; use yii\validators\Validator; class BothRequired extends Validator {
<?php
namespace app\components\validators;
use Yii;
use yii\validators\Validator;
class BothRequired extends Validator
{
public function validateAttribute($model, $attribute)
{
//validation code here
}
}
但是,此验证需要将一些参数传递给验证。在本例中,我需要发送第二个需要检查的属性。我似乎不知道如何做到这一点,如果我在模型本身中创建验证规则,那么我可以传递$params
,但我不知道如何传递到这个独立类
还有一点需要进一步说明,如果我可以拥有一个包含所有自定义验证器的类,而不是每个验证器一个文件,那么对我来说会更好
有什么想法吗
关于好的
在@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!');
}
}
}
模型规则
public function rules()
{
return [
['company_name', BothRequired::className(), 'other'=>'contact_name', 'skipOnEmpty' => false, ],
];
}
如您所见,在本例中,您必须声明要发送的属性是$other
,然后在代码中使用它作为$this->other
然后我可以验证这两个项目
我希望这事能澄清
利亚姆
另外,我提到的另一个问题。。。。如何将所有验证器放在一个类中?好的
在@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!');
}
}
}
模型规则
public function rules()
{
return [
['company_name', BothRequired::className(), 'other'=>'contact_name', 'skipOnEmpty' => false, ],
];
}
如您所见,在本例中,您必须声明要发送的属性是$other
,然后在代码中使用它作为$this->other
然后我可以验证这两个项目
我希望这事能澄清
利亚姆
另外,我提到的另一个问题。。。。如何将所有验证器放在一个类中?我的猜测是,如果验证器类中有属性,那么可以通过在规则中发送
'attribute'=>
来填充它们(就像'skipOnEmpty'一样,我打赌它是验证器的一个属性。
。这似乎是我应该做的事情。我尝试过传递各种变量,'params','other'。首先它抱怨它不是一个属性,然后如果我在类中将它设置为一个公共属性,其他什么都不会发生。谢谢,你把我推到了正确的位置例如,我将添加答案我猜如果您在validator类上有属性,那么您可以通过在规则中发送'attribute'=>
来填充它们(就像'skipOnEmpty'一样,我打赌它是验证器的一个属性。
。这似乎是我应该做的事情。我尝试过传递各种变量,'params','other'。首先它抱怨它不是一个属性,然后如果我在类中将它设置为一个公共属性,其他什么都不会发生。谢谢,你把我推到了正确的位置现在,我将补充答案