How to customize validation error message in Laravel?

Validation error message will display through the application blade files. As explained in validation in Laravel, the $errors variable is shared with all blades. It displays the corresponding error messages in the application view.

Validation error messages customization

Laravel has built-in validation rules. These are inside the lang/en/validation.php file. Each rule has a corresponding error message. In addition, there is also a translation entry for each rule. So you can copy them to another translation file for an additional language your application supports. This ensures error messages also get Laravel Localization support.

You can also customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages.

public function messages()
{
    return [
        'name.required' => 'A user name is required',
        'contact.required' => 'A contact number is required',
    ];
}

The code snippet above shows how to pass new string data to customize the error message for a specific parameter and validation criteria. For example, if the ‘required’ criteria of a user’s name fails. i.e. A user name is empty. You may change the error message to ‘A user name is required’, instead of the default error message.

Validation error messages JSON response

In case of validation fails of an XHR request, a JSON response will return. In this case if the application throws a Illuminate\Validation\ValidationException exception, Laravel automatically formats the error messages and returns a 422 Unprocessable Entity HTTP response.

{
    "message": "The user name must enter all details. (and 4 more errors)",
    "errors": {
        "user_name": [
            "The user name must be a string.",
            "The user name must be at least 1 characters."
        ],
        "authorization.role": [
            "The selected authorization.role is invalid."
        ],
        "users.0.email": [
            "The users.0.email field is required."
        ],
        "users.2.email": [
            "The users.2.email must be a valid email address."
        ]
    }
}

The code above shows an example of the JSON response format for validation errors. Nested attributes error keys will flatten into “dot” notation format.

The $error Directive

You can use the @error blade directive to instantly determine if validation error messages exist for a given attribute. Using the @error directive, you can echo a $message variable that displays the error message.

<label for="title">Post User Data</label>
 
<input id="user"
    type="text"
    name="user"
    class="@error('user') is-invalid @enderror">
 
@error('user')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Leave a Comment