skip to Main Content

I made a custom validation in Laravel 10.x blade using JavaScript and Bootstrap 5 classes. When I press the submit button, the store action doesn’t work, and the form is reloaded empty without putting data in the database.

Here is the code of the JavaScript validation in the blade:

<script> 
        function checkInput() 
            {
            var cognome = document.getElementById("cognome").value;
            var nome = document.getElementById("nome").value;
            var codFisc = document.getElementById("cod_fiscale").value;
            var area = document.getElementById("id_area").value;
            var check = 0;

            console.log("cognome: ", cognome);
            console.log("nome: ", nome);
            console.log("codFisc: ", codFisc);
            console.log("area: ", area);

            document.getElementById("cognome").classList.remove("is-invalid");
            document.getElementById("nome").classList.remove("is-invalid");
            document.getElementById("cod_fiscale").classList.remove("is-invalid");
            document.getElementById("id_area").classList.remove("is-invalid");  

            if (cognome == "")
                {
                    document.getElementById("cognome").classList.add("is-invalid");
                    check = 1;
                }

            if (nome == "")
                {
                    document.getElementById("nome").classList.add("is-invalid");
                    check = 1;
                }

            if (codFisc == "" || codFisc.length != 16)
                {
                    document.getElementById("cod_fiscale").classList.add("is-invalid");
                    check = 1;
                }        
            
            if (!id_area.value)
                {
                    document.getElementById("id_area").classList.add("is-invalid");
                    check = 1;
                }         

            console.log("check: ", check)    

            if (check == 0) 
                {
                    document.getElementById("cognome").classList.remove("is-invalid");
                    document.getElementById("nome").classList.remove("is-invalid");
                    document.getElementById("cod_fiscale").classList.remove("is-invalid");
                    document.getElementById("id_area").classList.remove("is-invalid");                        
                    document.getElementById("formUtente").submit();
                }
            }
</script>

And the next is the code of the form inside the blade:

                <form action="{{route('utenti.store')}}" method="post" name="formUtente" id="formUtente" role="form">
                @csrf                     
                    <div class="form-group">
                        <label for="Cognome">Cognome</label>
                        <input type="text" class="form-control" id="cognome" name="cognome">
                        <div class="invalid-feedback">Il cognome non deve essere vuoto.</div>
                    </div>

                    <div class="form-group">
                        <label for="Nome">Nome</label>
                        <input type="text" class="form-control" id="nome" name="nome">
                        <div class="invalid-feedback">Il nome non deve essere vuoto.</div>
                    </div>

                    <div class="form-group">
                        <label for="Codice Fiscale">Codice Fiscale</label>
                        <input type="text" class="form-control" id="cod_fiscale" name="cod_fiscale">
                        <div class="invalid-feedback">Il codice fiscale non deve essere vuoto e deve essere lungo 16 caratteri.</div>
                    </div>

                    <div class="form-group">
                        <label for="Attivo">Attivo</label>
                        <select class="form-select" id="attivo" name="attivo">
                            <option value="1" selected>Si</option>
                            <option value="0">No</option>
                        </select>                                                        
                    </div>

                    <div class="form-group">
                        <label for="Area">Area</label>
                        <select class="form-select" id="id_area" name="id_area">
                            <option value="">Selezionare un'area...</option>                                                                        
                                @foreach ($areas as $area)
                                    <option value="{{$area->id}}">{{$area->descrizione}}</option>
                                @endforeach
                        </select>
                        <div class="invalid-feedback">Selezionare un'area dalla lista.</div>                            
                    </div>

                    <div class="form-group">
                        <label for="Cognome">Note</label>
                        <textarea rows=5 class="form-control" id="note" name="note"></textarea>
                    </div>

                    <br>
                    <button type="button" class="btn btn-primary" id="controlBTN" onclick="checkInput();">Inserisci nuovo utente</button>
                </form>

I have tried other JS submit methods, but they don’t work.
The problem is that the submit button starts but doesn’t go to the controller for storing the data inside the database. The form works well without any validation.

Any suggestions?

2

Answers


  1. I recommend utilizing the Laravel-jsvalidate package, which can be found at the following link:

    https://github.com/proengsoft/laravel-jsvalidation
    

    or install using composer

    composer require proengsoft/laravel-jsvalidation
    

    You just need to add the following code to the form blade template:

    <!-- Laravel Javascript Validation -->
    <script type="text/javascript" src="{{asset('vendor/jsvalidation/js/jsvalidation.js')}}"></script>
    
    {!! JsValidator::formRequest('AppHttpRequestsMyFormRequest') !!}
    

    If you remove the JavaScript code, the controller validations will function correctly. i.e.

    $validate = $request->validate([
            'cognome' => 'required|string|max:25',
            'nome' => 'required|string|max:20',
            ...........
        ]);
    
    Login or Signup to reply.
  2. Don’t mess with the form when it submits. Use the build-in validation instead of creating you own. Use the required attribute on the form fields. If any form field is not valid, the form will not submit. On #cod_fiscale I also use the attribute maxLength. It will limit the length of the input. There are also other attributes that you can use for validation. Find them here: : The Input (Form Input) element

    document.forms.formUtente.addEventListener('invalid', e => {
      e.preventDefault();
      e.target.classList.add('is-invalid');
    }, true);
    
    document.forms.formUtente.addEventListener('input', e => {
      if(e.target.validity.valid){
        e.target.classList.remove('is-invalid');
      }
    });
    
    document.forms.formUtente.addEventListener('change', e => {
      if(e.target.validity.valid){
        e.target.classList.remove('is-invalid');
      }
    });
    div.invalid-feedback {
      visibility: hidden;
    }
    
    input.is-invalid ~ div.invalid-feedback {
      visibility: visible;
    }
    
    select.is-invalid ~ div.invalid-feedback {
      visibility: visible;
    }
    <form action="/test" method="post" name="formUtente" id="formUtente" role="form">
      <div class="form-group">
        <label for="Cognome">Cognome</label>
        <input type="text" class="form-control" id="cognome" name="cognome" required>
        <div class="invalid-feedback">Il cognome non deve essere vuoto.</div>
      </div>
    
      <div class="form-group">
        <label for="Nome">Nome</label>
        <input type="text" class="form-control" id="nome" name="nome" required>
        <div class="invalid-feedback">Il nome non deve essere vuoto.</div>
      </div>
    
      <div class="form-group">
        <label for="Codice Fiscale">Codice Fiscale</label>
        <input type="text" class="form-control" id="cod_fiscale" name="cod_fiscale" required maxLength="15">
        <div class="invalid-feedback">Il codice fiscale non deve essere vuoto e deve essere lungo 16 caratteri.</div>
      </div>
    
      <div class="form-group">
        <label for="Attivo">Attivo</label>
        <select class="form-select" id="attivo" name="attivo">
          <option value="1" selected>Si</option>
          <option value="0">No</option>
        </select>
      </div>
    
      <div class="form-group">
        <label for="Area">Area</label>
        <select class="form-select" id="id_area" name="id_area" required>
          <option value="">Selezionare un'area...</option>
          <option value="1">Item 1</option>
          <option value="2">Item 2</option>
          <option value="3">Item 3</option>
        </select>
        <div class="invalid-feedback">Selezionare un'area dalla lista.</div>
      </div>
    
      <div class="form-group">
        <label for="Cognome">Note</label>
        <textarea rows=5 class="form-control" id="note" name="note"></textarea>
      </div>
    
      <br>
      <button type="submit" class="btn btn-primary" id="controlBTN">Inserisci nuovo utente</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search