12

In Login form, I need to have glyphicon-remove icon at the end of every validation message with the corresponding field names. So I used below code in the 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 HTML code (<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.

Siva.G ツ
  • 811
  • 1
  • 7
  • 20

2 Answers2

29

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

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}

7ochem
  • 2,035
  • 1
  • 29
  • 37
Alfred_P
  • 792
  • 4
  • 8
2

Add this in your form:

_form.php

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

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

GAMITG
  • 3,670
  • 7
  • 30
  • 50
Insane Skull
  • 8,810
  • 9
  • 38
  • 59