Personalized messages with Validator

Asked

Viewed 909 times

0

I can’t apply custom rules to my forms, every time I try to apply some rule, it returns a ValidationException pattern of Laravel, how would you make the error message to be customized?

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CriarContaPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [

            'nome' => 'required | max:255 | alpha',


        ];

    }

    public function messages()
    {

        return [

            'nome.required' => 'Nome obrigatório',
            'nome.max' => 'Nome deve ter até 150 caracteres',
            'nome.alpha' => 'Nome deve possuir apenas caracteres',      

        ];

    }

}

But even before I try to test this validation, I use the command to list my routes, and in the terminal itself it returns me:

   Illuminate\Validation\ValidationException  : The given data was invalid.

  at vendor\laravel\framework\src\Illuminate\Foundation\Http\FormRequest.php:130
          * @throws \Illuminate\Validation\ValidationException
         */
         protected function failedValidation(Validator $validator)
         {
           throw (new ValidationException($validator))
                         ->errorBag($this->errorBag)
                         ->redirectTo($this->getRedirectUrl());
         }


  Exception trace:

  1   Illuminate\Foundation\Http\FormRequest::failedValidation(Object(Illuminate\Validation\Validator))
      vendor\laravel\framework\src\Illuminate\Validation\ValidatesWhenResolvedTrait.php:26

  2   Illuminate\Foundation\Http\FormRequest::validateResolved()
      vendor\laravel\framework\src\Illuminate\Foundation\Providers\FormRequestServiceProvider.php:30

What should I do so that the message does not appear as "The Given data was invalid", but something personified?

I currently use the version 6.0 from Laravel, I tried to look for something related in the documentation but ended up not finding

  • What version of Laravel?

1 answer

2


Oops, let’s try to solve your problem.

I’ll pass an example that is working and is a good practice for validation in Laravel.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Cliente;

class ClienteController extends Controller {

  public function store(Request $request) {

    $mensagens = [
        'required' => 'O :attribute é obrigatório!',
        'nome.min' => 'É necessário no mínimo 5 caracteres no nome!',
        'email.email' => 'Digite um email válido!'
    ];

    $request->validate([
        'nome' => 'required|min:5|max:10|unique:clientes',
        'idade' => 'required',
        'email' => 'required|email'
    ], $mensagens);

    $cliente = new Cliente();

    $cliente->nome = $request->input('nome');
    $cliente->idade = $request->input('idade');
    $cliente->endereco = $request->input('endereco');
    $cliente->email = $request->input('email');
    $cliente->save();
  }
}

Note that in the code above is defined the validations that I want to use, as required, min, email etc. Then is made an assignment of the field I want to use with validation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.