Yii2 - How to add custom error messages on input fields

12,198

Solution 1

So basically all I did was add

'message' => 'Current password cannot be blank.' 

to my rules.

Make sure you seperate the correct rules, so you don't get that message on multiple fields, where it doesn't make sense. Also make sure you add it on the 'required' rule, unless you want that message to show when it's another rule..

I hope this helped you guys, as I spent a bit too much time searching for it.

Solution 2

From what you described it seems that you changed the label displayed in the form, not attribute label.

No need to duplicate error message and separate attributes to different rules, for most of the cases changing the attribute label in attributeLabels() method is enough.

That way if you change the language of application, it will show correct error message.

In your model:

public function attributeLabels()
{
    return [
        ...
        'password_hash' => 'Current password',
    ];
}

All default validators take the label of attribute from this section, if it's not defined it will be transformed to "Password Hash".

Share:
12,198
Paramone
Author by

Paramone

Programming enthusiast

Updated on June 05, 2022

Comments

  • Paramone
    Paramone almost 2 years

    In my database I named 'password' as 'password_hash' so automatically I'd get 'password_hash' in my error message, even tho I changed the label to 'Current password'.

    Example:

    enter image description here

    What I want is:

    enter image description here