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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32477486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:00:17  来源:igfitidea点击:

Yii2, Custom validation message with attribute names

phpyii2yii2-modelyii2-validation

提问by Siva.G ツ

In Login form, I need to have glyphicon-removeicon at the end of every validation message with the corresponding field names. So I used below code in the Login model.

在登录表单中,我需要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>']

Instead of this above code, Is there any possible way to use something like the below code.

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

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

The idea of the above code is to get corresponding field name dynamically for every fields.

上面代码的思路是为每个字段动态获取对应的字段名。

Please do the needful. Thanks.

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

Update

更新

The HTMLcode (<span class="glyphicon glyphicon-remove"></span>) here I've used is output correctly by using encode=>'false'. But what I need is instead of defining separately for every fields, need to define commonly for all fields.

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

回答by Alfred_P

You can use {attribute}in your message to reference the attribute name.

您可以{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'],
  ];
}

You can also use the other options set in the validator like {min}or {requiredValue}

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

回答by Insane Skull

Add this in your form:

在您的表单中添加:

_form.php

_form.php

<?php
   $form = ActiveForm::begin([
            'options' => ['enctype' => 'multipart/form-data'],
            'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'help-block']] 
   ]);
?>

errorOptionsdefault encoding is true so, your html code is encoded as message, so it won't work until you set 'encode' => false.

errorOptions默认编码为 true,因此,您的 html 代码被编码为消息,因此在您设置'encode' => false.