The button
without an attribute type
, within a form
, has the function of submit
. When cancelling the event click
from the button you are at the same time canceling Submit. With this HTML5 validations will be ignored because they depend on Submit. That is, when placing event.preventDefault();
you are canceling the effects of clicking the button, which would be to submit the form. Therefore, without submitting the form, the validations have no effect.
If you want to prevent the form from being sent but do the validations normally capturing the click on the button, you can use the method .one()
jQuery. It will create a Event Handler from Ubmit which will run only 1 time each time you validate all the form fields, and then you can cancel Ubmit at that event. But first you need to check all fields with the attribute required
were completed.
The estate elemento.validity.valid
returns true or false in accordance with the required
element (can be used with other types of validations, such as the pattern
, for example). Just scroll through the elements containing the attribute required
, and if any is not valid, changes the variable to false
avoiding the method .one()
. If all fields are valid, the method .one()
with the event Submit will be activated and the preventDefault()
will prevent sending.
$("#troca-senha").on("click", function (event) {
console.log("cliquei!");
var valido = true;
$("form [required]").each(function(index, element){
if(!element.validity.valid){
valido = false;
return;
}
});
if(valido){
// aqui chama o submit, mas é cancelado pelo preventDefault()
$("form").one("submit", function(event){
console.log("Evento submit cancelado");
event.preventDefault();
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="post" class="form-reseta-senha">
<label>Email</label>
<input type="email" name="email" class="inputbox" autocomplete="on" id="email" required />
<label>CPF/CNPJ</label>
<input type="text" name="cpfcnpj" class="inputbox mascara-cpfcnpj" id="cpfcnpj" autocomplete="on" required maxlength="18" min="14" />
<label>Nova senha</label>
<input type="password" name="senha" class="inputbox" id="senha" autocomplete="off" required />
<label>Confirme a nova senha</label>
<input type="password" name="confirmacaoSenha" id="confirmacaoSenha" class="inputbox" autocomplete="off" required />
<button class="btn btn-full btn-primary" id="troca-senha">
<div class="btn-texto">Trocar senha</div>
<i class="fas fa-spinner fa-spin white md-24" id="icon-btn" style="display:none"></i>
</button>
</form>
reminded of Return???
– Leandro Angelo
Post the code so we can help
– Albertt Santos
These HTML5 validations only work on Submit.
– Sam
I put the code there, I don’t have much knowledge in javascript, I already do the validation in backend wanted to just 'force' the user to fill the fields correctly
– Rafael Scheffer