An interesting solution
This way just put data-required="Preencha seu nome!"
in the input text you want putting the error message and so you will no longer need to modify the javascript for the new fields you create, and also you can create new custom validations with the same idea.
Upshot
Code comments are explaining how it works
//Função para cuidar da mensagem de erro
function setaMensagem(seletor, mensagem){
//Verifica se já existe uma mensagem de erro
if(seletor.next().attr("class") == 'erro'){
seletor.next().text(mensagem); //Se existir apenas seta a mensagem
}else{
seletor.after("<small class='erro'>" + mensagem + "</small>");//Se não cria uma mensagem nova
}
}
function validar(element){
if(element.val().length <= 0){
setaMensagem(element, element.data('required'));
return false;
}else{
setaMensagem(element, "");
return true;
}
}
$(function() {
$("[data-required]").on('blur', function() {
validar($(this));
});
$('#formtest').submit(function() {
return validar($("[data-required]"));
});
})
input.erro {
border: 1px solid red;
}
.erro {
color: red;
padding-left: .3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formtest">
<label>Nome</label>
<br>
<input
type="text"
id="nome"
value=""
data-required="Preencha seu nome!">
<!-- Defino apenas a mensagem de erro -->
<small class='erro'></small>
<input type="submit" value="submit">
</form>
Solving using your code
Red error message
For the error message to be set only once I have directly placed the html tag
<small class='erro'></small>
Since it is empty it will not be visible, and in the code Javascript
I put it this way
$this.next().text("Preencha seu nome!");
It takes the next element using the method next
, which in this case is the tag small
and arrow the text, in case it seven again it replace the previous text not thus repeating the text.
And finally I replace the following excerpt
$("small").remove();
for
$("small").text("");
So it just manipulates the text, since the small without text as stated above does not appear if there is no text.
Alert
But in case you want to limit the alert
, I created a flag with a variable as I did in the case "Tudocerto", thus the alert
appear only once.
The operation is simple, the flag is set to true, and when displaying the message it is set to false, if the event is called again the message does not appear since the flag will be false.
Upshot
$(function() {
var tudoCerto = true;
var $form = $("#formtest");
$("#nome").on('blur', function() {
var $this = $("#nome"),
$value = $this.val();
if ($value == "") {
$form.submit(function() {
return false;
});
if ($this.hasClass('.error')) {
$this.removeClass("erro");
} else {
$this.addClass("erro");
$this.next().text("Preencha seu nome!");
}
} else {
$this.removeClass("erro");
$("small.erro").text("");
if(tudoCerto){
alert("tudo certo!");
tudoCerto = false;
}
$form.submit(function() {
return true;
});
}
})
})
input.erro {
border: 1px solid red;
}
.erro {
color: red;
padding-left: .3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formtest">
<label>Nome</label>
<br>
<input type="text" id="nome" value="">
<small class='erro'></small>
<input type="submit" value="submit">
</form>
thanks for your reply, helped too much! wanted to understand this logic of it having to be before to check, I could explain?
– Gabriel Rodrigues Dias
I forgot to ask, how do you check when you press Submit too...?
– Gabriel Rodrigues Dias