Problem with i18n support and validation messages

I have added support for German language to my app, but I noticed that although Yii now shows the error messages in German, they are not really fully German since it uses name of field in the message which still is in English. For example if I have an input field with name=“first_name” that is required and I post the field empty, the error displayed reads like this:

First Name darf nicht leer sein.

This is neither German nor English and that the word “Name” is capitalised which makes the message look weird. Is this a short-coming of Yii or am I doing something wrong?

Also can I set Yii to always use the label of an input field instead of its name attribute to generate the error message? I’m asking this because labels need to be localized anyways as they are visible to the user, unlike name attribute which remain hidden from the user. Or is there another way to fix this problem, that is except replacing every single rule with a custom validation rule?

1 Like

Hi @smohadjer,

You can use Model::attributeLabels() to define the localized names of model attributes.

For example:

    public function attributeLabels()
        return [
            'id' => 'ID',
            'status' => \Yii::t('app', 'Status'),
            'first_name' => \Yii::t('app', 'First Name'),

Thanks so much @softark. This was a great tip. I wish this would have been mentioned in Yii’s validation guide/documentation.