Yii2自定义验证需正确调用addError()添加错误,并通过attributeLabels()和{attribute}占位符实现中文提示;复杂逻辑宜封装为继承Validator的独立类,支持服务端与客户端同步验证。

Yii2 自定义验证返回错误信息,核心在于两处控制:一是验证逻辑中如何添加错误,二是错误提示文本如何定制化显示。只要理清这两层,中文提示、动态字段名、多语言支持都能轻松实现。
验证方法里正确调用 addError()
无论用内联函数还是独立验证类,失败时必须调用 $model->addError($attribute, $message),不能 return false 或 throw 异常。例如:
- 内联写法(写在 rules() 中):
[['phone'], function ($attribute) { if (!preg_match('/^1[3-9]d{9}$/', $this->$attribute)) { $this->addError($attribute, '手机号格式不正确'); } }] - 独立方法写法(模型内定义 public 方法):
public function validatePhone($attribute, $params) { if (empty($this->$attribute) || !is_numeric($this->$attribute)) { $this->addError($attribute, '请输入有效的数字电话'); } }
对应规则:[['phone'], 'validatePhone']
让错误提示显示中文字段名
默认错误信息会显示英文字段名(如 phone can not be blank)。要改成“手机号不能为空”,需两步配合:
- 在模型中定义 attributeLabels() 方法:
public function attributeLabels() { return ['phone' => '手机号']; } - 在规则中使用 {attribute} 占位符:
[['phone'], 'required', 'message' => '{attribute}不能为空']
这样最终提示就是:“手机号不能为空”。
复用性高或逻辑复杂的场景用独立验证类
比如身份证校验、邮箱域名白名单、密码强度等,适合封装成类。类必须继承 yiialidatorsValidator,并重写 validateAttribute():
- 类名以 Validator 结尾(如 IDCardValidator)
- 支持传参,例如:
['id_card', 'IDCardValidator', 'strict' => true],其中public $strict = false;就是可配置属性 - 错误仍用
$this->addError($model, $attribute, $message)添加
客户端验证同步(可选但推荐)
默认自定义验证只在服务端触发。如需表单失焦时也校验,得补充 clientValidateAttribute() 方法,返回合法 JavaScript 字符串。例如:
- 在独立验证类中:
public function clientValidateAttribute($model, $attribute, $view) { return "if (!/^1[3-9]\d{9}$/.test(value)) { messages.push('手机号格式不正确'); }"; } - 确保 ActiveForm 开启了客户端验证:
['enableClientValidation' => true]
不复杂但容易忽略











