Yii2, Custom Validation Message with Attribute Names

In the login form, I need to have the glyphicon-remove icon at the end of each validation message with the corresponding field names. Therefore, I used the code below 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, above the code, is there any possible way to use something like the code below.

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

The idea of ​​the code above is to get a dynamic field name for each field.

Please do the necessary. Thanks.

Update

The HTML code ( <span class="glyphicon glyphicon-remove"></span> ) that I used is correctly displayed using encode=>'false' . But I need instead of defining separately for each field, I need to define usually for all fields.

+7
php yii2 yii2-validation yii2-model
source share
2 answers

You can use {attribute} in your message to refer to 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 other parameters set in the validator, for example {min} or {requiredValue}

+16
source share

Add this to your form:

_form.php

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

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

+1
source share

All Articles