Error returning validation messages with Form Request in Laravel

Asked

Viewed 343 times

-1

Hey there, guys! I’m trying to return custom validation messages with Laravel’s Form Request, I’ve already put the validations inside "public Function Rules()", and custom messages inside "public Function messages()", but the messages are not returned, Can you help me? NOTE: The form has some fields generated by a FOR, when I remove these fields, the messages are displayed. IMPORTANT: These fields generated by FOR are not being validated in Form Request, they are not included in the validation. CONSOLE ERROR: The following message appears on the console: set-Cookie header is Ignored in Response from url 127.0.0.1:8000 Cookie length should be Less than or Equal to 4096 characters.

// VIEW ONDE SE ENCONTRA O FORMULÁRIO

@section('conteudo')

<section class="content-header">
    <h3>Cadastrar registro:</h3>
// CÓDIGO PARA EXIBIR MENSAGENS DE VALIDAÇÃO
    @if(isset($errors) && count($errors) > 0)
        @foreach ($errors->all() as $error)
            {{$error}}
        @endforeach
    @endif

</section>

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <!-- Horizontal Form -->
            <div class="box box-info">                 
                <div class="box-body">
                    <div class="form-group">
                        <form action="{{ route('contestacao.create') }}" autocomplete="off" class="form-horizontal" name="cadastrar-tabulacao" id="cadastrar-tabulacao" method="POST">  
                            @csrf  
                            <div class="col-sm-8">
                                <div class="alert alert-success alert-dismissible" id="notificacao-sucesso" style="display:none">
                                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                    <h4><i class="icon fa fa-check"></i> Notificação!</h4>
                                    O documento foi cadastro com sucesso.
                                </div>
                                <div class="alert alert-danger alert-dismissible" id="notificacao-erro" style="display:none">
                                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                    <h4><i class="icon fa fa-ban"></i> Notificação!</h4>
                                    Erro ao cadastrar o registro.
                                </div> 
                                <h4>Dados do cliente:</h4>
                                <div class="form-group">    
                                    <div class="col-sm-8">                            
                                    <label for="nome_cliente">Nome do cliente: <span class="text-red"> *</span></label>
                                        <input type="text" minlength="5" maxlength="120" class="form-control required" name="nome_cliente" id="nome_cliente" placeholder="Digite o nome do cliente" >
                                    </div>
                                </div>
                                <div class="form-group">    
                                    <div class="col-sm-4">                            
                                    <label for="documento">Documento: <span class="text-red"> *</span></label>
                                        <input type="text" minlength="11" maxlength="14" class="form-control required" name="documento" id="documento" placeholder="CPF ou CNPJ" >
                                    </div>
                                    <div class="col-sm-4">                            
                                    <label for="instancia">Instância:</label>
                                        <input type="text" minlength="10" maxlength="10" class="form-control required" name="instancia" id="instancia" placeholder="Digite a instância">
                                    </div>
                                    <div class="col-sm-4">                            
                                    <label for="pcobranca">Conta cobrança: <span class="text-red"> *</span></label>
                                        <input type="text" minlength="12" maxlength="14" class="form-control required" name="pcobranca" id="pcobranca" placeholder="Digite o perfil de cobrança" >
                                    </div>
                                </div>

                                <h4>Dados do ajuste:</h4>
                                <div class="form-group">    
                                    <div class="col-sm-6">                            
                                        <label for="motivo">Motivo: <span class="text-red"> *</span></label>
                                        <select class="form-control select2 required" id="motivo" name="motivo" style="width: 100%;" >
                                            <option value="">Escolha uma opção</option>
                                            <option>Acionamento Indevido</option>
                                            <option>Atraso Na Mudança De Endereço</option>
                                        </select>
                                    </div>
                                    <div class="col-sm-6">                            
                                        <label for="tipocontest">Tipo Contestação: <span class="text-red"> *</span></label>
                                        <select class="form-control required" id="tipocontest" name="tipocontest" >
                                            <option value="">Escolha uma opção</option>
                                            <option>Ajuste</option>
                                            <option>Acordo</option>
                                        </select>   
                                    </div>
                                </div>
                                <div class="my-form-group">
                                    <div class="my-table-itens-title" style="width: calc(100% - 17px)">
                                        <div class="my-form-control my-title col-sm-2" style="font-size: 22px;"><span class="fa fa-arrow-circle-down"></span></div>
                                        <div class="my-form-control my-title col-sm-2">Venc Fatura</div>
                                        <div class="my-form-control my-title col-sm-2">Valor fatura</div>
                                    </div>
                                    <div class="my-table-itens">
                                        @php ($number_itens = 13)
                                        @for ($i = 0; $i < $number_itens; $i++)
                                            <div class="my-form-group">
                                                <div class="my-form-control col-sm-2" style="background-color: #e6ebef;">{{ $i + 1 }}</div>                                        
                                                <input type="text" name="vencimento_fatura[]" class="my-form-control col-sm-2 datepicker" minlength="8" >
                                                <input type="text" name="valor_fatura[]"  class="my-form-control col-sm-2 valor-contestacao" minlength="3" >
                                                <input type="text" name="valor_solicitado[]"  class="my-form-control col-sm-2 valor-contestacao" minlength="3" >
                                                <input type="text" name="valor_contestado[]"  class="my-form-control col-sm-2 valor-contestacao" minlength="3" >
                                                <select type="text" name="tipo_correcao[]" class="my-form-control col-sm-2" >
                                                    <option value="">----</option>
                                                    <option>Boleto</option>
                                                    <option>Conta Futura</option>
                                                    <option>Reembolso</option>
                                                </select>
                                            </div>
                                        @endfor
                                    </div>
                                </div>
                                <input type="hidden" name="number_itens" value="{{ $number_itens }}">
                                <h4>Dados de Causa Raiz:</h4>
                                <div class="form-group">    
                                    <div class="col-sm-4">                            
                                        <label for="causa_raiz">Causa Raiz: <span class="text-red"> *</span></label>
                                        <select id="causa_raiz" name="causa_raiz" class="form-control select2 required" style="width: 100%;" >
                                            <option value="">Escolha uma opção</option>
                                            <option>Sem necessidade de correção</option>
                                            <option>Acionamento Indevido</option>
                                            <option>Atribuir Exceção</option>
                                            <option>Atribuir REQ</option>
                                        </select>
                                    </div>
                                    <div class="col-sm-4">                            
                                        <label for="correcao_realizada">Correção Realizada: <span class="text-red"> *</span></label>
                                        <select id="correcao_realizada" name="correcao_realizada" class="form-control required">
                                            <option value="">Escolha uma opção</option>
                                            <option>Sim</option>
                                            <option>Não</option>
                                            <option>N/A</option>
                                        </select>
                                    </div>
                                </div>
                                <h4>Fechamento da Solicitação:</h4>
                                <div class="form-group">    
                                    <div class="col-sm-4">                            
                                    <label for="matricula_primeiro_nivel">Colaborador 1º nível:</label>
                                        <input id="matricula_primeiro_nivel" minlength="5" maxlength="15" name="matricula_primeiro_nivel" type="text" class="form-control required" placeholder="Matrícula completa">
                                    </div>
                                    <div class="col-sm-4">                            
                                    <label for="fechamento_analise">Fechamento da análise: <span class="text-red"> *</span></label>
                                        <select id="fechamento_analise" name="fechamento_analise" class="form-control required" >
                                            <option value="">Escolha uma opção</option>
                                            <option>Procedente</option>
                                            <option>Procedente Parcial</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-sm-12"> 
                                    <label for="anotacoes">Anotações: <span class="text-red"> *</span></label>
                                        <textarea form="cadastrar-tabulacao" id="anotacoes" name="anotacoes" class="form-control required" rows="5"></textarea>
                                        {{-- <textarea form="cadastrar-tabulacao" name="anotacoes2" id="" cols="30" rows="10"></textarea> --}}
                                    </div>
                                </div>
                                <!-- /.box-body -->
                                <div class="box-footer">
                                    <button type="reset" id="limpar_formulario" class="btn btn-danger">Limpar</button>
                                    <button type="submit" id="cadastrar_contestacao" class="btn btn-success pull-right" onclick="return confirm('Tem certeza que deseja cadastrar o registro?')">Cadastrar Contestação</button>
                                </div>
                                <!-- /.box-footer -->
                            </div>
                        </form>
                        <div class="col-sm-4">
                            <h4>Suas tratativas:</h4>
                            <div class="small-box bg-green">
                                <div class="inner">
                                    <p>Registros realizados hoje:</p>
                                    <h3 id="registros-hoje">50</h3>
                                </div>
                                <div class="icon">
                                    <i class="fa fa-thumbs-o-up"></i>
                                </div>
                                <a href="meus_registros" class="small-box-footer">
                                Ver meu histórico geral <i class="fa fa-arrow-circle-right"></i>
                                </a>
                            </div>
                            <div class="small-box bg-yellow">
                                <div class="inner">
                                    <p>Registros pendentes, sem solução:</p>
                                    <h3 id="registros-abertos">30</h3>
                                </div>
                                <div class="icon">
                                    <i class="fa fa-folder-open-o"></i>
                                </div>
                                <a href="registros_pendentes" class="small-box-footer">
                                Ver meus registros sem solução <i class="fa fa-arrow-circle-right"></i>
                                </a>
                            </div>
                            <div class="col-sm-12">
                                <div class="form-group">    
                                    <form name="queda_chamada" id="queda_chamada" method="post">
                                        @csrf                            
                                        <label for="documento" style="font-weight: 400;">Use o botão abaixo para registrar uma queda de ligação.</label>
                                        <div class="box-footer">
                                            <button type="submit" id="registrar_queda" class="btn btn-block btn-danger" onclick="return confirm('Tem certeza que deseja registrar ligação caiu?')"><span class="fa fa-phone"></span> Registrar queda de chamada</button>
                                        </div> 
                                    </form>
                                </div> 
                            </div>
                            <h4>Cálcular período (n° dias):</h4>
                            <div class="col-sm-12">
                                <div class="box-body">
                                    <div class="form-group">  
                                        <div class="col-sm-6">                            
                                        <label for="data-inicio">Data inicial: <span class="text-red"> *</span></label>
                                            <input type="text" id="data-inicio" minlength="10" maxlength="10" class="form-control datepicker" >
                                        </div>
                                        <div class="col-sm-6">                            
                                        <label for="data-fim">Data final: <span class="text-red"> *</span></label>
                                            <input type="text" id="data-fim" minlength="10" maxlength="10" class="form-control datepicker" >
                                        </div>                                   
                                    </div> 
                                </div> 
                                <div class="box-footer">
                                    <button type="button" id="btn-calcular-periodo" class="btn btn-block btn-success"><i class="fa fa-calendar"></i> Calcular período</button>
                                </div>
                                <div>Número de dias no intervalo selecionado: <b id="numero-dias"></b></div>
                            </div>
                        </div>
                    </div>
                </div>                
            </div>
            <!-- /.box -->
        </div>
    </div>
</section>
@endsection

// CONTROLLER CRIADO

namespace App\Http\Controllers;

use App\Http\Requests\MesaRequest;

class MesaController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function contestacao_index()
    {
        return view('services.inicio');

    }

    public function contestacao_create(MesaRequest $request)
    {
         // NÃO INSERI NADA AINDA, ESTOU APENAS TESTANDO AS VALIDAÇÕES      
    }

}


// REQUEST CRIADO PARA DEFINIR AS VALIDAÇÕES E MENSAGENS

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MesaRequest 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_cliente' => 'required',
            'documento' => 'required',
            'pcobranca' => 'required',
            'motivo' => 'required',
            'tipocontest' => 'required',
            'anotacoes' => 'required',                         
            'fechamento_analise' => 'required', 
            'correcao_realizada' => 'required',                       
        ];
    }

    public function messages()
    {
        return [
            'nome_cliente.required' => 'O campo "Nome do cliente" é obrigatório!',
            'documento.required' => 'O campo "Nome do cliente" é obrigatório!',
            'pcobranca.required' => 'O campo "Conta cobrança" é obrigatório!',
            'motivo.required' => 'O campo "Motivo" é obrigatório!',
            'tipocontest.required' => 'O campo "Tipo Contestação" é obrigatório!',
            'anotacoes.required' => 'O campo "Anotações" é obrigatório!', 
            'fechamento_analise.required' => 'O campo "Fechamento" é obrigatório!', 
            'correcao_realizada.required' => 'O campo "Correçao" é obrigatório!', 
        ];        
    }
}

  • may happen of some, input is incorrect, check inputs, check fillables, expose your problem with more details.

  • @Andrémartins, I saw that when the error happens, the following message is generated in the console: set-Cookie header is Ignored in Response from url 127.0.0.1:8000 Cookie length should be Less than or Equal to 4096 characters. The form I created has many fields, I did a test and decreased the amount of fields and the problem did not occur... I believe something is limiting the amount of form fields.

  • check out this link: https://laravel.com/docs/5.8/validation#a-note-on-optional-Fields

  • Put View and Controller to the question

  • Hello all right? Are the inputs array type? Or are more than 6 inputs with different names? Because there is no such limitation of 6 required fields in a request. I use with several and no error at all. A close example of what you are doing have on my github on this link (the request is within the controller and the view).

  • @Virgilionovic I put the view, the controller and request in the question to explain better, interesting that when I comment the line " App Http Middleware Encryptcookies::class" inside the file "App Http kernel.php", the problem ceases to occur.

  • @Luizfernando, in fact, the form has several fields and I am validating only a few. When I decrease the amount of fields, the problem ceases to occur and messages are displayed.

  • It must be wrong configuration when coming home I create an answer

  • The point is that when your input is an array that is <input name='document[]>' in the Rules you must specify: 'document. *' => 'required' and no messages: 'documento.*.required' => 'Um documento é obrigatório', . Since you have simple inputs and inputs that are an array, as you have not done so for the inputs with array it is not displaying correctly. When you put * it refers to all elements with name of the input you specified, in my example, 'document'.

  • @Luizfernando, I took the array type and put the name of the input concatenated with the variable $i, example: name="expiration_invoice{{ $i + 1 }}", but the error still persists, what intrigues is that the fields generated within this "For" are not being validated. When I remove the fields generated by "For" the problem ceases to exist. Somehow the fields generated by "For" are causing the problem.

  • This way using the for and a counter is another way to validate inputs that are array-like, it’s a more laborious way. I prefer to use the field. * that * means it will apply to all fields that have the name field. Try using "*" to see if the problem does not occur. Because before I figured out how to use validation in inputs of type array it gave the same thing that yours is giving.

  • @Luizfernando, strange is that if I comment on the "messages" function of the request, the problem ceases to exist and the messages are displayed in English. Note that the fields generated by For are not being validated within the request, I do not include them in the validation.

  • Get it, try to run this command to display the messages and see what happens and tell me here: @if($errors->any())&#xA; @foreach($errors->all() as $erro)&#xA; {{$erro}}&#xA; @endforeach&#xA;@endif

  • @Luizfernando, I did this and the problem persists, the messages are not presented. The console continues to display the message: set-Cookie header is Ignored in Response from url http://127.0.0.1:8000/ Cookie length should be Less than or Equal to 4096 characters. Somehow, the input fields, even if not validated, are causing some conflict to customize the messages.

  • I saw that the problem ceases to exist when I try ONE of these two things: 1. When I comment on the "messages" function of the request even leaving the inputs generated by for, the messages are displayed in English. 2. when I remove the fields generated by for, custom messages work perfectly.

  • Well I don’t quite understand how this Encrypting Cookie works, but what it is saying is that it has a limit of 4096 characters for the cookie. In the case that you use for elements within my-table-iten, you are not adding an id to each one which is interesting because each input is a different element, it may be that since you did not specify id it is storing all of the same name in the same cookie and generating the error. It’s a theory, try to add the ids. Commenting on the messages is not a good idea.

  • If you want to comment the messages by leaving the automatic messages, you will have to translate the returns into Portuguese and then you do this: https://github.com/lucascudo/laravel-pt-BR-localization .

  • put with id, however the problem persists kkk I’ve tried everything, I’ve never seen a problem like this. thanks for the tip of the en-br.

Show 13 more comments

1 answer

0

I solved the problem by changing the version of Laravel, I was using 6.x. I changed the project to version 5.8 and the problem stopped occurring.

Browser other questions tagged

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