Validate fields with jQuery

2

I have a function in jQuery , which when the user clicks the next button it triggers an email.

When I click the button, I need to verify that the Name , Email and Phone fields have been filled out and, if not completed, low 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>
    
asked by anonymous 16.05.2018 / 18:33

2 answers

1

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

You can enter a div default after the field with .after with the corresponding message. This div can have 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 return prevents the script from continuing.

The whole code looks 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><scriptsrc="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>
    
16.05.2018 / 19:12
1

You do not need to implement this with Jquery. html itself already does this type of validation:

Simply put the required attribute 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*">

It is enough that the submit button on your form is of 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, html will already do the validation you need.

    
17.05.2018 / 19:29