logo
podcast Podcast
get help Get Unstuck

When would you use validation attributes?

Very useful in specific circumstances

Joel Clermont
Joel Clermont
2024-07-16

When you define field names in your validation rules, those names are used in the error messages when validation fails.

For example, with the required rule, the default error message is "The :attribute field is required." and :attribute is replaced with the field name.

I really like to stick with default error messages, but sometimes this can cause a less-readable error message.

Continuing the above example, if I had a field named dob, the error message would be "The dob field is required." which is not as clear as "The date of birth field is required."

In this case, though, instead of trying to customize the error, I'd just change the field name to date_of_birth to be more readable.

But every once in a while, you come across a scenario where you either can't change the field name or the field name will get displayed in an odd way.

Let's say you had a field for translated text, where the field name matched the target locale, like en-GB.

That error message would read: "The en- g b field is required." which would look very weird to a user with the extra spaces. Laravel is interpreting capital letters as the start of a new word, which in this case produces a very odd result.

In these very limited cases, I would add an attribute mapping to the language file for validation:

// lang/en/validation.php
'attributes' => [
    'en-GB' => 'en-GB', // or whatever label makes sense for your users
],

Laravel also lets you also specify an attributes method in your form request, or inline if constructing a validator manually. But I prefer to keep these changes centralized in the language file, not spread out across different files.

Here to help,

Joel

P.S. Sticking with the defaults leads to more maintainable Laravel apps. If your app has strayed from the defaults, we can help get it back in shape.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.