我必须实现标题中提到的验证,即两个字段(email、phone)中的任意一个是必填字段。
[['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\验证器\内联验证器::0'
有什么帮助吗?
3条答案
按热度按时间rjee0c151#
如果您不在乎当用户提供两个字段中的任何一个时两个字段都显示错误:
此解决方案比其他答案更短,并且不需要新的验证器类型/类:
如果您希望有一个自定义的错误消息,只需设置
message
选项:zysjyyx42#
规则应该是:
和法:
edqdpe6u3#
改进的变体
添加了**'skipOnEmpty'=〉false**用于强制验证,并且'other'可以是数组