Livewire: Incorrect validation attribute for model keys

Created on 10 Sep 2020  路  3Comments  路  Source: livewire/livewire

Description

When validating model keys such as user.first_name, the validation attribute in the error message becomes first_name.
The first_name field is required.

However, when validating a non-model value e.g. first_name, the validation attribute does correctly show first name.
The first name field is required.

Also, when validating model keys, validation attribute localization (defined in e.g. resources/lang/en/validation.php) is not taken into account.

Steps to reproduce

Context

  • Livewire version: 2.1.3
  • Laravel version: 8.0.3
  • Browser: Firefox

Most helpful comment

Yes, this was an oversight. Livewire intelligently removes the model name from the model attribute for validation messages.

This is fine except for when you want to register custom attributes to change something like post.title in a custom attribute.

The next version will have this fixed and you can properly set global attribute overrides: c8d1e37

All 3 comments

Livewire's automatic nested model attribute stripping uses Laravel's custom validator attributes. However, Laravel skips the attribute processing (getting translations, adding spaces) for custom attributes. This results in e.g. user.first_name to be displayed as first_name and also doesn't allow you to translate it. What do you think would be the best solution @calebporzio?

+1 also seeing this issue in 2.2.1.

the validation messages are ugly. I managed to fix them in SOME situations by adding a custom messages block to my livewire component like so:

public function messages()
    {
        return [
            'user.first_name.required' => 'First name is required',
            'user.last_name.required' => 'Last name is required',
            'region.id.required' => 'Please select a region',
        ];
    }

However these messages don't seem to apply anymore once you try and use the "validateOnly($propertyName)" method. So in other words, I found a workaround for regular validation with $this->validate(), but not for $this->validateOnly... which I need.

EDIT: I think it may be fixed in 2.2.3 at least for my workaround

Yes, this was an oversight. Livewire intelligently removes the model name from the model attribute for validation messages.

This is fine except for when you want to register custom attributes to change something like post.title in a custom attribute.

The next version will have this fixed and you can properly set global attribute overrides: c8d1e37

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mokhosh picture mokhosh  路  3Comments

zaherg picture zaherg  路  4Comments

ChrisJohnson-83 picture ChrisJohnson-83  路  4Comments

nickpoulos picture nickpoulos  路  3Comments

bardh7 picture bardh7  路  3Comments