Yii2,带属性名称的自定义验证消息

时间:2015-09-09 10:48:26

标签: php yii2 yii2-model yii2-validation

在登录表单中,我需要在每条验证邮件末尾都有glyphicon-remove图标,并带有相应的字段名称。所以我在Login model中使用了以下代码。

['email', 'required', 'message' => 'Email cannot be blank<span class="glyphicon glyphicon-remove"></span>'],
['password', 'required', 'message' => 'Password cannot be blank<span class="glyphicon glyphicon-remove"></span>']

代替以上代码,是否有任何可能的方法来使用类似下面的代码。

[['email', 'password'], 'required', 'message' => $attribute.' cannot be blank<span class="glyphicon glyphicon-remove"></span>']

上述代码的想法是为每个字段动态获取相应的字段名称。

请做必要的事。感谢。

更新

我使用的HTML代码(<span class="glyphicon glyphicon-remove"></span>)是使用encode=>'false'正确输出的。但我需要的是不是为每个字段单独定义,而是需要为所有字段共同定义。

1 个答案:

答案 0 :(得分:24)

您可以在邮件中使用{attribute}来引用属性名称。

public function rules()
  {
    return [
      [
        ['email','password', 'password_verify', 'alias', 'fullname'],
        'required',
        'message' => '{attribute} is required'
      ],
      [['email'], 'email'],
      [['fullname'], 'string', 'max' => 50],
      [['password', 'password_verify'], 'string', 'min' => 8, 'max' => 20],
      [['password_verify'], 'compare', 'compareAttribute' => 'password'],
  ];
}

您还可以使用验证程序中设置的其他选项,例如{min}{requiredValue}

相关问题