我必须实现标题中提到的验证,即需要两个字段之一(电子邮件,电话).我在我这样做model
:
[['email'],'either', ['other' => ['phone']]],
这是方法:
public function either($attribute_name, $params) { $field1 = $this->getAttributeLabel($attribute_name); $field2 = $this->getAttributeLabel($params['other']); if (empty($this->$attribute_name) && empty($this->$params['other'])) { $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required.")); return false; } return true; }
当我访问我的索引页面时,它给了我这个错误:
异常(未知属性)'yii\base\UnknownPropertyException',消息'设置未知属性:yii\validators\InlineValidator :: 0'
有帮助吗?
规则应该是:
['email', 'either', 'params' => ['other' => 'phone']],
方法:
public function either($attribute_name, $params) { $field1 = $this->getAttributeLabel($attribute_name); $field2 = $this->getAttributeLabel($params['other']); if (empty($this->$attribute_name) || empty($this->{$params['other']})) { $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required.")); } }
如果您不关心当用户都不提供两个字段时两个字段都显示错误:
此解决方案比其他答案短,并且不需要新的验证器类型/类:
$rules = [
['email', 'required', 'when' => function($model) { return empty($model->phone); }],
['phone', 'required', 'when' => function($model) { return empty($model->email); }],
];
如果您想获得自定义的错误消息,只需设置以下message
选项:
$rules = [
[
'email', 'required',
'message' => 'Either email or phone is required.',
'when' => function($model) { return empty($model->phone); }
],
[
'phone', 'required',
'message' => 'Either email or phone is required.',
'when' => function($model) { return empty($model->email); }
],
];