HTML5 validation before preventing form submission

Asked

Viewed 352 times

1

I’m capturing the event of clique on a button of a form and I am using the preventDefault() not to send the form, but by doing so the validation of the HTML 5 (required, email, maxlength) doesn’t work, how can I fix it?

<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>
    @Html.AntiForgeryToken()
</form>


$("#troca-senha").on("click", function (event) {
event.preventDefault();
console.log("cliquei!");});
  • 1

    reminded of Return???

  • Post the code so we can help

  • 2

    These HTML5 validations only work on Submit.

  • 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

3 answers

2


The problem is that you are treating the event click, which occurs before actual submission, and before validation:

$("#troca-senha").on("click", function (event) { 
   event.preventDefault();
   console.log("cliquei!");
});

The event you need to capture is the submit form, so the validation will run first:

$("form").on("submit", function (event) { 
   event.preventDefault();
   console.log("cliquei!");
});

If necessary, add an id to the form to refer to it.

  • is in Submit anyway, I just want to validate the basics with html and send the request via ajax. I already knew the event Ubmit but I did not care that the click comes before... thanks !

0

If you are only using HTML5 validation, there is no need for any javascript including the preventDefault(), only one form, with an input required and a Ubmit button

Example:

<!DOCTYPE html>
<html>
  <body>
    <form action="#" method="POST">
      <input type="text" name="nome" required>
      <button type="submit">Enviar</button>
    </form>
  </body>
</html>

Now, if you want to do your own validation via javascript, you should use the event onsubmit and a method that returns whether the form should be sent and not in the event of click button...

function validar(){
  if(document.getElementById("nome").value == "teste")
    return false;  
}
<!DOCTYPE html>
<html>

<body>
  <form action="#" method="POST" onsubmit="return validar()">
    <p>não pode ser igual a "teste"</p>
    <input type="text" name="nome" id="nome" required>
    <button type="submit">Enviar</button>
  </form>
</body>

</html>

  • I won’t validate with js, just change the click event by Submit, thanks

0

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>

Browser other questions tagged

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