簡體   English   中英

Yii2,帶屬性名稱的自定義驗證消息

[英]Yii2, Custom validation message with attribute names

在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>']

而不是上面的代碼,有沒有任何可能的方法來使用類似下面的代碼。

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

上述代碼的思想是為每個字段動態獲取相應的字段名稱。

請只做那些需要的。 謝謝。

更新

我使用的HTML代碼( <span class="glyphicon glyphicon-remove"></span> )通過使用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}

在表單中添加:

_form.php這個

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

errorOptions默認編碼為true,因此,您的html代碼被編碼為消息,因此在您設置'encode' => false之前它將無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM