JavaScript form validation does not function properly in Laravel 10.x

I implemented a custom validation in Laravel 10.x blade using JavaScript and Bootstrap 5 classes. However, upon clicking the submit button, the store action fails to work, resulting in the form being reloaded empty without saving any data into the database.

Below is the JavaScript code for the validation within 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>

Next, here is the form code inside the blade file:

                <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>

                    /* Additional form fields omitted for brevity */

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

Despite trying various other JS submission methods, the issue persists. The submit button appears to trigger but does not direct the data to the controller for storage in the database. Everything functions correctly when there are no validations applied.

Any advice or suggestions?

Answer №1

One great tool to enhance your Laravel form validations is the Laravel-jsvalidate package. You can easily access it through this link:

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

Alternatively, you can install it using composer by running the following command:

composer require proengsoft/laravel-jsvalidation

To implement this package in your project, simply include the code snippet below in your form blade template:

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

{!! JsValidator::formRequest('App\Http\Requests\MyFormRequest') !!}

If you decide to remove the JavaScript code, rest assured that the controller validations will still work seamlessly. For example:

$validate = $request->validate([
        'cognome' => 'required|string|max:25',
        'nome' => 'required|string|max:20',
        ...........
    ]);

Answer №2

Ensure the form submits smoothly by utilizing built-in validation rather than creating your own. Add the required attribute to form fields for easy validation. To limit input length on #cod_fiscale, use the maxLength attribute. Explore other validation attributes here.

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">Surname</label>
    <input type="text" class="form-control" id="cognome" name="cognome" required>
    <div class="invalid-feedback">Surname cannot be empty.</div>
  </div>

  <div class="form-group">
    <label for="Nome">Name</label>
    <input type="text" class="form-control" id="nome" name="nome" required>
    <div class="invalid-feedback">Name cannot be empty.</div>
  </div>

  <div class="form-group">
    <label for="Codice Fiscale">Tax Code</label>
    <input type="text" class="form-control" id="cod_fiscale" name="cod_fiscale" required maxLength="15">
    <div class="invalid-feedback">Tax code must not be empty and must be 16 characters long.</div>
  </div>

  <div class="form-group">
    <label for="Attivo">Active</label>
    <select class="form-select" id="attivo" name="attivo">
      <option value="1" selected>Yes</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="">Select an 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">Select an area from the list.</div>
  </div>

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

  <br>
  <button type="submit" class="btn btn-primary" id="controlBTN">Add new user</button>
</form>

Answer №3

After some digging, I uncovered the issue: the required field in the controller had a different name than the input id, causing Laravel validation to fail silently without returning any error code. Once I aligned the validation settings inside the controller correctly, I was able to quickly identify and rectify the error.

Thank you for your assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Select2: When using a remote select2 control, the tab key press does not allow for the selection of the highlighted

I have set up select2 to load ajax data into select2 based on the example provided in this link Load ajax data into select2. In the example, I can type text, use arrow keys to navigate, and then hit tab to select the highlighted item. However, in my case, ...

Running a Blitz.js api handler triggers a Google Cloud Storage call failure with the message "error:0909006C:PEM routines:get_name:no start line"

When attempting to utilize @google-cloud/storage within a Blitz.js /api handler, I encounter the following error: error:0909006C:PEM routines:get_name:no start line at Sign.sign (internal/crypto/sig.js:110:29) at NodeCrypto.sign (C:\Users&bsol ...

What is causing my Directive to trigger the error "Error: $injector:unpr Unknown Provider"?

I have been diligently working on updating my Controllers, Factories, and Directives to align with the recommended Angular Style Guide for Angular Snippets. So far, I have successfully refactored the Controllers and Factories to comply with the new style ...

Using the Facebook marketing API requires a valid Instagram account ID to be provided as a parameter

I've been exploring the capabilities of the Facebook Marketing API once again. After successfully creating Facebook ads using my Node.js app, I now have my sights set on Instagram. My current call to create an AdCreative looks like this: fb.api(&ap ...

Fade-in a new, revised text after fading-out the original text in ReactJS

I have a bunch of p elements that I'd like to cycle through, fading in one at a time and then replacing it with the next. Here is the jQuery example on CodePen: https://codepen.io/motion333/pen/EBBGVM Now, I'm attempting to achieve the same effe ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

Encountered a static symbol values resolution error while working with angular 2 npm link. The issue occurred when the function 'makeDecorator' was being called

Whenever I attempt to use "npm link" to consume a different package I created, I encounter an error while running my application. The error message reads as follows: An error occurred while resolving symbol values statically during the invocation of the ...

JSON parsing throws an error due to encountering an 'unexpected end of input' issue

Here's some code I'm working with: var default_links = '{ "name" : "Google", "url": "https://encrypted.google.com/", "fav_url": "https://encrypted.google.com/favicon.ico" }\n'+ '{ "name" : "Yahoo", "url": "http://www. ...

Which programming language or technology utilizes the syntax <%VARIABLE%> and in what context is it employed?

First things first, I want to clarify that I'm not a developer, so this might be a simple question. Despite my research indicating that ASP typically uses this syntax, it's important to note that it is not the case here. I am currently delving i ...

Transferring request body data between routes in Express: A guide

In my MERN application, there are two specific routes in place. The first route is designated for 'Storing Data' and is referred to as the 'data' route. The second route is used for 'Register User' functionalities and is known ...

Using Ajax to send a JSON object containing two arrays to a servlet, then parsing it in a Java servlet without the use

When sending data to a servlet, I utilize an Ajax POST call to send a JSON object containing two arrays. In the servlet class in Java, I need to read this data sent in two lists or arrays. I am avoiding the use of jQuery for the Ajax call and am not very f ...

What are the steps to retrieve raw messages from Gmail using Node.js?

I'm attempting to retrieve the complete email message data, including body content, using the raw format option specified in the gmail api reference. Unfortunately, it doesn't appear to be functioning correctly. Here is the code I'm using: ...

The 3D sphere in Three.js appears to have a 2D visual effect

Hey there! I've recently delved into the world of three.js and I'm working on creating a captivating scene with 3D spheres and a simple rotation using orbit controls. However, I've encountered an issue where the spheres appear flattened or 2 ...

Determine whether an item in a RadGrid is currently in Edit mode using Javascript

Looking for a solution with a telerik RadGrid where I need to determine if a GridDataItem is in edit mode. Preferably using JavaScript. I know how to do this with VB, but I want to achieve it on the client side. Additionally, I would appreciate assistan ...

Is there a method in VBA to access elements generated by javascript code?

After spending several hours conducting thorough research on Google (including browsing StackOverflow), I've been trying to find a method that would allow me to target HTML elements generated by JavaScript in VBA. For instance, using ie.Document.getE ...

Is there a way to specifically remove only the last row from a table?

Recently, I encountered a problem with my JS code that adds and removes table rows based on user interaction. Adding rows functioned perfectly, but the issue arose when attempting to delete rows. Instead of deleting only the last row as intended, all rows ...

Pause autoplay in Bootstrap v5.0 Carousel when a carousel item is clicked

I've been attempting to disable the carousel autoplay using jQuery after clicking on a carousel item, but all my efforts have been unsuccessful. Can anyone provide some assistance? Thank you! This is what I've tried so far: $(".carousel-i ...

What steps should be taken to trigger an API call once 3 characters have been entered into a field

In my current project, I am dealing with a parent and child component setup. The child component includes an input field that will emit the user-entered value to the parent component using the following syntax: <parent-component (sendInputValue)="g ...

`Select a new preview image by clicking on the provided images`

Check out the following code snippet showcasing the implementation of a preview image and a list of images on a web page: <div class="col-lg-5 text-center"> <img src="img/1.jpeg"> //preview image <hr> ...

Add a custom Leaflet JS control button with personalized text and hover functionality

I successfully completed a control-button-leaflet tutorial and it worked for me. Now I have some additional requirements: Show some text when hovering over the button (similar to the zoom buttons) Change the button's color when hovering over it Abil ...