Yii2,带有属性名称的自定义验证消息
Yii2, Custom validation message with attribute names
在登录表单中,我需要在每个验证消息的末尾都有 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'
正确输出的。但是我需要的不是为每个字段单独定义,而是需要为所有字段共同定义。
在您的表单中添加:
_form.php
<?php
$form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'],
'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'help-block']]
]);
?>
errorOptions
默认编码为真,因此,您的 html 代码被编码为消息,因此在您设置 'encode' => false
.
之前它不会工作
您可以在消息中使用 {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}
在登录表单中,我需要在每个验证消息的末尾都有 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'
正确输出的。但是我需要的不是为每个字段单独定义,而是需要为所有字段共同定义。
在您的表单中添加:
_form.php
<?php
$form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'],
'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'help-block']]
]);
?>
errorOptions
默认编码为真,因此,您的 html 代码被编码为消息,因此在您设置 'encode' => false
.
您可以在消息中使用 {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}