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?