Problem alerting when validating fields

Asked

Viewed 50 times

1

I have a problem in the message that is printed from the validation of my form, it is only printed correctly when the last field is not filled or is filled, or the problem is in the execution of the loop. Follow 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";
            }
        }
    }
}

2 answers

2


It looks like he checks every element, and what’s gonna count is just the last one. Because in the previous ones he’s putting it unfilled, but in the last one, if it’s filled out, it’ll overwrite the previous one.

My solution is to force i to be equal to the size of elements, so it already exits the loop when value is empty or you can use while and exit the loop when the value of the element 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";
            }
        }
    }
}
  • Thank you very much! It worked perfectly, although I was looking to keep the has-error class on all elements that pointed error and not only the first of them, but I’ve already managed.

  • Look man, what you can do for this, is at the end (outside the loop) check if there is any element with the class 'has-error', ai sim vc puts the div with the error message, if this class is existing.

  • I did it the way below, it’s a little more extensive, but it already works

2

Solution for all blank fields to be highlighted and 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");
}

}

Browser other questions tagged

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