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";
}
}
}
}
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.
– Leo Lima
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.
– Ikaro Pinheiro
I did it the way below, it’s a little more extensive, but it already works
– Leo Lima