Yii2中的模型形式规则和验证

时间:2018-02-02 22:57:13

标签: php yii yii2

例如,我有模型repartition

MySubmitForm

在这里,我有两个必需参数(use yii\base\Model; class MySubmitForm extends Model{ public $value1; public $value2; public $value3; public function rules(){ return [['value1', 'value2'],'required']; } } $value1),我希望其中一个参数 ,或者我希望用户只有在两个{{{ 1}}和$value2将为空。

我可以通过此表单模型实现此目的吗?

1 个答案:

答案 0 :(得分:1)

您可以在验证规则中使用自定义验证功能。

可能的选择:

1)选择最重要的相关字段并为其添加错误。

2)选择多个重要的相关字段并向其添加相同的错误消息(我们可以在传递以保留代码DRY之前在单独的变量中存储和传递消息)。

3)我们可以使用不存在的属性名称来添加错误,让我们说all,因为此时不会检查属性是否存在。

public function rules()
{
    return [['value1', 'value2'],'yourCustomValidationMethod'];
}

public function yourCustomValidationMethod()
{
    // Perform custom validation here regardless of "name" attribute value and add error when needed
    if ($this->value1=='' && $this->value2=='') {
        //either use session flash 
        Yii::$app->session->setFlash('error','You need to provide one of the fields');

        //or use model error without any specific field name 
        $this->addError('all', 'Your error message');
    }            
}

请注意,您可以使用session flashmodel通知您喜欢的错误

相关问题