Search code examples
laravellaravel-5laravel-validation

Using form request specific custom validation attributes


Using Laravel's localization (http://laravel.com/docs/5.1/localization) I have created some custom validation attributes to provide friendlier validation errors (for instance, 'First Name' instead of first name etc).

I am using form requests (http://laravel.com/docs/5.1/validation#form-request-validation) in order to validate user submissions and there are scenarios where I would like to provide store-specific custom validation attributes (for instance, I may have a 'name' field that is Brand Name in one context, and Product Name in another).

The messages() method allows me to specify validation rule specific message overrides, but that isn't ideal as it's not the validation message as such we need to override, just the attribute name (for example, if we have 5 validation rules for 'email', we have to provide 5 overrides here, rather than one override for, let's say, Customer Email).

Is there a solution to this? I note references to formatValidationErrors() and formatErrors() in the Laravel documentation, but there is not really any information on how to correctly override these, and I've not had much luck in trying.


Solution

  • You can override the attribute names, which is defaulting to whatever the field name is.

    With form request

    In your form request class override the attributes() method:

    public function attributes()
    {
        return [
            'this_is_my_field' => 'Custom Field'
        ];
    }
    

    With controller or custom validation

    You can use the 4th argument to override the field names:

    $this->validate($request, $rules, $messages, $customAttributes);
    

    or

    Validator::make($data, $rules, $messages, $customAttributes);
    

    Simple working example

    Route::get('/', function () {
        // The data to validate
        $data = [
            'this_is_my_field' => null
        ];
    
        // Rules for the validator
        $rules = [
            'this_is_my_field' => 'required',
        ];
    
        // Custom error messages
        $messages = [
            'required' => 'The message for :attribute is overwritten'
        ];
    
        // Custom field names
        $customAttributes = [
            'this_is_my_field' => 'Custom Field'
        ];
    
        $validator = Validator::make($data, $rules, $messages, $customAttributes);
    
        if ($validator->fails()) {
            dd($validator->messages());
        }
    
        dd('Validation passed!');
    });