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

Siv*_*G ツ 12 php yii2 yii2-model yii2-validation

在Login窗体中,我需要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>']
Run Code Online (Sandbox Code Playgroud)

而不是上面的代码,有没有任何可能的方法来使用类似下面的代码.

[['email', 'password'], 'required', 'message' => $attribute.' cannot be blank<span class="glyphicon glyphicon-remove"></span>']
Run Code Online (Sandbox Code Playgroud)

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

请只做那些需要的.谢谢.

更新

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

小智 27

您可以{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'],
  ];
}
Run Code Online (Sandbox Code Playgroud)

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