簡體   English   中英

Yii2自定義獨立驗證

[英]Yii2 Custom Standalone Validation

好的,我相信我將進行許多自定義驗證,因此我決定根據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
    }
}

這是模型

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

但是,此驗證需要將一些參數傳遞給驗證,在此示例中,我需要發送需要檢查的第二個屬性。 我似乎無法解決該問題,如果我在模型本身中創建驗證規則,則可以傳遞$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

然后,我可以驗證兩個項目。

我希望這可以清除它

利亞姆

PS:我提到的另一點是...。如何將所有驗證器歸為一類?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM