Laravel - How to override the validation message?

Asked

Viewed 482 times

0

I have a Request that validates through a class Request:

The Controller:

  public function store(PagtoRequest $request)
  {
   ... resto da lógica

A Request:

namespace App\Http\Requests;


use App\Rules\ValidarValor;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;


class PagtoRequest extends FormRequest
{
  public function authorize()
  {
    return true;
  }



  public function rules(Request $request)
  {

    $arrayParcelas = $request->input("arrayParcelas"); // guardando no dados das percelas


    return [
      'arrayParcelas.*.vcto_parcela' => ['required','date_format:"d/m/Y"'], // verifica se as datas informadas são válidas
      'arrayParcelas.*.valor_parcela' => ['required',new ValidarValor], // verifica se os valores informados são válidos
    ];
  }

  public function messages() {
    return [
      'arrayParcelas.*.vcto_parcela.date_format' => 'Existem parcelas com datas inválidas',
      'arrayParcelas.*.valor_parcela.ValidarValor' => 'Existem parcelas com valores inválidos',
    ];
  }
}

A Rule:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ValidarValor implements Rule
{
  public function __construct()
  {

  }

  public function passes($attribute, $value)
  {
    // verifica se está no formato 9.999.999.999,99 e quantos milhares forem necessários.
    $expressao = "/^([1-9]{1}[\d]{0,2}(\.[\d]{3})*(\,[\d]{0,2})?|[1-9]{1}[\d]{0,}(\,[\d]{0,2})?|0(\,[\d]{0,2})?|(\,[\d]{1,2})?)$/";
    return (preg_match($expressao,$value));
  }

  public function message()
  {
    return "O campo :attribute está no formato incorreto.";
  }
}

The first rule, I can customize the error message because I use an Laravel validation rule (in the case of field validation vcto_parcela)

But in the case where I use the Rule ValidarValor, how to personalize the message?

The way I did, it doesn’t work because it’s returning to Rule’s message instead of the message I set in Request.

That is, (exemplifying if one of the portions is in incorrect format) is returning this message (coming from Rule):

O campo arrayParcelas.2.valor_parcela está no formato incorreto.

Instead of this, which I set in Request:

Existem parcelas com valores inválidos.

Of course, that’s because this isn’t right:

'arrayParcelas.*.valor_parcela.ValidarValor' => 'Existem parcelas com valores inválidos',

But how to do so to display the error message I set, when I use a Rule?

  • It does not deserve a 'no' vote, another 'no' vote that has not been adopted

  • Post the entire request @

  • removes Request from the method public function rules(Request $request) leaving as the standard public function rules()?

  • I edited the question with all the information

1 answer

0


Analyzing the code and what the us provides to validate data with customized classes What you’ve done is just the way it is, it works that way, of course there’s a way around can add functionality to this class so that when a message is passed in your constructor may have the option to use a new validation message, example:

<?php namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ValidarValor implements Rule
{
    private $message;
    public function __construct($message = null)
    {
        $this->message = $message;
    }
    public function passes($attribute, $value)
    {
        $expressao = "/^([1-9]{1}[\d]{0,2}(\.[\d]{3})*(\,[\d]{0,2})?|[1-9]{1}[\d]{0,}(\,[\d]{0,2})?|0(\,[\d]{0,2})?|(\,[\d]{1,2})?)$/";
        return (preg_match($expressao,$value));
    }
    public function message()
    {
        return $this->message ?? 'O campo :attribute está no formato incorreto.';
    }
}

with this change made in your contructor now has the possibility to change the default message of your rule as follows:

<?php namespace App\Http\Requests;

use App\Rules\ValidarValor;
use Illuminate\Foundation\Http\FormRequest;

    class PagtoRequest extends FormRequest
    {
        public function authorize()
        {
            return true;
        }
        public function rules()
        {
            return [
                'valor_parcela' => [
                    'required', 
                     new ValidarValor('Existem parcelas com valores inválidos') // passe aqui !!!
                ]
            ];
        }

        public function messages()
        {
            // remova somente aquele validação que foi customizada na classe
            return [

            ];
        }
    }

References

  • Perfect. Very good. Thank you!

Browser other questions tagged

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