Validate fields with jQuery

Asked

Viewed 4,419 times

2

I have a function in jQuery, that when the user clicks on the button next he fires an e-mail.

When you click the button I need it to check the fields Name, Email and Telephone have been completed and if not completed report below the input Por favor preencha o campo x

$("#proximo").click(function(){

    var settings = {
      // "async": true,
      // "crossDomain": true,
      "url": "script.php",
      "method": "POST",
      "headers": {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      "data": {
        "nome": $("#nome").val(),
        "email": $("#email").val(),
        "celular": $("#celular").val()
      }
    };

    $.ajax(settings).done(function (response) {

      console.log(response); 

    });

});
<form method="post">
<label>Nome Completo*</label>
<input id="nome" minlength="5" type="text" class="form-control" name="nome" placeholder="Nome Completo*">

<label>E-mail Válido*</label>
<input id="email" type="email" class="form-control" name="email" placeholder="Email Válido*">

<label>Telefone Válido*</label>
<input id="celular" type="text" class="form-control"  name="celular" placeholder="Telefone">

<button type="button" name="submit" class="next action-button" id="proximo" value="Próximo"> Próximo</button> 
</form>

  • To place a message below the field accurately, you need to know how this form is formatted on the page. You can post a print of how it appears on the screen?

  • http://tinypic.com/r/25k4j6a/9

2 answers

1


In my view the attribute minlength does not exist, so in Javascript I will check if the string size is less than 5.

You can enter a div standard after field with .after with its message. This div can have the class .erromsg. In CSS I set a red color for the message text:

.erromsg{
   color: #f30; /* cor do texto */
}

And in the event that takes the click and calls Ajax, I check the fields this way:

// remove as mensagens de erro
$(".erromsg").remove();

// verificar se os campos foram preenchidos
var nome = $("#nome");
var email = $("#email");
var telefone = $("#celular");

// Mensagem de erro padrão a ser inserida após o campo
var erromsg = '<div class="erromsg">Preencha o campo <span></span></div>';

if(!nome.val() || nome.val().length < 5){
   nome.after(erromsg);
   $(".erromsg span").text("nome corretamente");
   return;
}

if(!email.val()){
   email.after(erromsg);
   $(".erromsg span").text("email");
   return;
}

if(!telefone.val()){
   telefone.after(erromsg);
   $(".erromsg span").text("telefone");
   return;
}

When a field is empty, I enter the message and the return prevents the script from proceeding.

The whole code goes like this:

$("#proximo").click(function(){

   // remove as mensagens de erro
   $(".erromsg").remove();

   // verificar se os campos foram preenchidos
   var nome = $("#nome");
   var email = $("#email");
   var telefone = $("#celular");
   
   // Mensagem de erro padrão a ser inserida após o campo
   var erromsg = '<div class="erromsg">Preencha o campo <span></span></div>';
   
   if(!nome.val() || nome.val().length < 5){
      nome.after(erromsg);
      $(".erromsg span").text("nome corretamente");
      return;
   }

   if(!email.val()){
      email.after(erromsg);
      $(".erromsg span").text("email");
      return;
   }

   if(!telefone.val()){
      telefone.after(erromsg);
      $(".erromsg span").text("telefone");
      return;
   }
   

    var settings = {
      // "async": true,
      // "crossDomain": true,
      "url": "script.php",
      "method": "POST",
      "headers": {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      "data": {
        "nome": $("#nome").val(),
        "email": $("#email").val(),
        "celular": $("#celular").val()
      }
    };

    $.ajax(settings).done(function (response) {

      console.log(response); 

    });

});
.erromsg{
   color: #f30; /* cor do texto */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<form method="post">
<label>Nome Completo*</label>
<input id="nome" type="text" class="form-control" name="nome" placeholder="Nome Completo*">

<label>E-mail Válido*</label>
<input id="email" type="email" class="form-control" name="email" placeholder="Email Válido*">

<label>Telefone Válido*</label>
<input id="celular" type="text" class="form-control"  name="celular" placeholder="Telefone">

<button type="button" name="submit" class="next action-button" id="proximo" value="Próximo"> Próximo</button> 
</form>

  • Got it! I tried to do similar but it didn’t work within my click event, another question, when I click the next button, I step to a second step of the form which in this case is the class. next, you have the possibility of making this validation without going to the next step and only going to the next step after the 3 fields are filled?

  • Yes, the validation I put prevents that by clicking the "next" button Ajax is only called if the 3 fields have been filled.

1

You don’t need to implement this with Jquery. Jquery itself html already makes this kind of validation:

Just put the attribute required in the input you want to be mandatory. Ex

<input required id="nome" minlength="5" type="text" class="form-control" name="nome" placeholder="Nome Completo*">

And it is enough that the send button of your form is of the type submit. Ex:

<button type="submit" name="submit" class="next action-button" id="proximo" value="Próximo"> Próximo</button> 

With only these 2 attributes, the html will already do the validation you need.

  • Only it will not be possible to see the validation in the location that it set "below the input" and yes it will be in accordance with the default of the browser.

  • Most browsers by default display validation messages below their respective inputs . Ex: Chrome, Firefox

  • Exhibit how to.

Browser other questions tagged

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