Problem warning when validating fields

1

I have a problem in the message that is printed from the validation of my form, it only prints correctly when the last field is not filled or is filled, ie the problem is in the execution of the loop. Here is my HTML code:

<form id="formulario">
    <div class="form-group">
        <label class="control-label">Nome Completo</label>
        <input id="nomeCompleto" type="text" name="nome" class="form-control" maxlength="40" onkeypress="return letras()">
    </div>
    <div class="form-group">
        <label class="control-label">Modelo do Veículo</label>
        <input id="modeloDoVeiculo" type="text" name="modelo" maxlength="40" class="form-control">
    </div>
    <div class="form-group">
        <label class="control-label">Placa do Veículo</label>
        <input id="placaDoVeiculo" type="text" name="placa" class="form-control" maxlength="8">
    </div>
    <div class="alert text-center" id="apareceAlerta" style="display:none"></div>
    <div class="form-group text-center">
        <input type="submit" name="adicionar" value="Adicionar" class="btn btn-primary" onclick="alertaCadastro()">
    </div>
</form>

And my JavaScript code:

var formulario = document.getElementById("formulario");
formulario.addEventListener("submit",cadastrarVeiculo);
function cadastrarVeiculo(evento){
    evento.preventDefault();
    for(var i = 0; i < this.elements.length; i++){
        var elemento = this.elements[i];
        if (elemento.type != "submit") {
            alertaDeCadastro = document.getElementById("apareceAlerta");
            let isValid;
            if (elemento.value == "") {
                elemento.parentNode.classList.add("has-error");
                alertaDeCadastro.classList.remove("alert-success");
                alertaDeCadastro.classList.add("alert-danger");
                alertaDeCadastro.innerHTML = "Os campos acima não foram preenchidos corretamente!";
                alertaDeCadastro.style.display = "block";
            }else{
                elemento.parentNode.classList.remove("has-error");
                alertaDeCadastro.classList.remove("alert-danger");
                alertaDeCadastro.classList.add("alert-success");
                alertaDeCadastro.innerHTML = "Cadastro realizado com sucesso!";
                alertaDeCadastro.style.display = "block";
            }
        }
    }
}
    
asked by anonymous 06.10.2017 / 17:05

2 answers

2

It looks like it checks all the elements, and it's only the last one that counts. Because in the previous one it is putting not filled, but in the last, if it has filled, it will overwrite the previous one.

My solution is to force i to be equal to the size of elements, so it already exits the loop at the time the value is empty or you can use the while and exit the loop when the element value is empty:

var formulario = document.getElementById("formulario");
formulario.addEventListener("submit",cadastrarVeiculo);
alertaDeCadastro= '';
function cadastrarVeiculo(evento){
    evento.preventDefault();

    for(var i = 0; i < this.elements.length; i++){
        var elemento = this.elements[i];
        if (elemento.type != "submit") {
            alertaDeCadastro = document.getElementById("apareceAlerta");
            let isValid;
            if (elemento.value == "") {
                elemento.parentNode.classList.add("has-error");
                alertaDeCadastro.classList.remove("alert-success");
                alertaDeCadastro.classList.add("alert-danger");
                alertaDeCadastro.innerHTML = "Os campos acima não foram preenchidos corretamente!";
                alertaDeCadastro.style.display = "block";
                i = this.elements.length;
            }else{
                elemento.parentNode.classList.remove("has-error");
                alertaDeCadastro.classList.remove("alert-danger");
                alertaDeCadastro.classList.add("alert-success");
                alertaDeCadastro.innerHTML = "Cadastro realizado com sucesso!";
                alertaDeCadastro.style.display = "block";
            }
        }
    }
}
    
06.10.2017 / 18:00
2

Workaround so that all blank fields are highlighted, not just the first one:

var formulario = document.getElementById("formulario");
formulario.addEventListener("submit",cadastrarVeiculo);
function cadastrarVeiculo(evento){
var nomeCompleto = document.getElementById("nomeCompleto"),
modeloDoVeiculo = document.getElementById("modeloDoVeiculo"),
placaDoVeiculo = document.getElementById("placaDoVeiculo"),
horaEntrada = new Date();
var isValid;
evento.preventDefault();
for(var i = 0; i < this.elements.length; i++){
    var elemento = this.elements[i];
    if (elemento.type != "submit") {
        alertaDeCadastro = document.getElementById("apareceAlerta");
        if (elemento.value == "") {
            elemento.parentNode.classList.add("has-error");
            if ((nomeCompleto.value == "")||(modeloDoVeiculo.value == "")||(placaDoVeiculo.value == "")) {
                alertaDeCadastro.classList.remove("alert-success");
                alertaDeCadastro.classList.add("alert-danger");
                alertaDeCadastro.innerHTML = "Os campos acima não foram preenchidos corretamente!";
            }
            alertaDeCadastro.style.display = "block";
        }else{
            elemento.parentNode.classList.remove("has-error");
            alertaDeCadastro.classList.remove("alert-danger");
            alertaDeCadastro.classList.add("alert-success");
            alertaDeCadastro.innerHTML = "Cadastro realizado com sucesso!";
            isValid = true;
            if ((nomeCompleto.value == "")||(modeloDoVeiculo.value == "")||(placaDoVeiculo.value == "")) {
                alertaDeCadastro.classList.remove("alert-success");
                alertaDeCadastro.classList.add("alert-danger");
                alertaDeCadastro.innerHTML = "Os campos acima não foram preenchidos corretamente!";
                isValid = false;
            }
            alertaDeCadastro.style.display = "block";
        }
    }
}
if (isValid == true) {
    console.log("cadastrou");
}

}

    
06.10.2017 / 18:24