Input Validation with javascript

0

Good afternoon, I have a form where I built a function to validate unfilled fields. But when I start filling in some fields and I leave some empty and I click on the submit button to submit anyway.

HTML:

                <div class="form-group col-md-4">
                <label>Fabricante:</label>
                <select class="form-control mensalidade required">
                        <option selected="selected" disabled="disabled">Selecione Algo</option>
                        <option value="1">algo</option>
                </select>
            </div>
            <div class="form-group col-md-4">
              <label for="inputNome">Produto:</label>
              <input type="text"  placeholder="Produto" id="produto" class="form-control required" >
            </div>
            <div class="form-group col-md-4">
                <label>Modelo:</label>
                <input type="text" placeholder="Modelo" id="modelo" class="form-control required">
            </div>
            <div class="form-group col-md-4">
              <label for="inputNome">Número de serie:</label>
                <input type="text"  placeholder="Numero de serie" id="numeroserie" class="form-control required">
            </div>
            <div class="form-group col-md-4">
              <label for="inputNome">Tensão:</label>
                <select class="form-control mensalidade required" id="tensao" required="">
                    <option selected="selected" disabled="disabled">Selecione a Tensão</option>
                    <option value="1">110</option>
                    <option value="2">220</option>
                    <option value="3">Bivolt</option>
                </select>
            </div>
            <div class="form-group col-md-4">
              <label for="inputNome">Versão:</label>
                <input type="text"  placeholder="Versão do produto (se houver)" id="versao" class="form-control required">
            </div>
           <div class="form-group col-md-12">
              <label>Descrição:</label>
              <textarea placeholder="Escreva uma descrição do problema" rows="3"  class="form-control required"></textarea>
            </div>
            <div class="box-footer col-md-12">
                <button class="btn btn-warning" type="button" onclick="validarCampos()">Abrir OS</button>
            </div>

Javascript

        function validarCampos(){
        var retorno;
        $(".required").each(function() {
                if($(this).val() === '' || $(this).val() === null){
                    $(this).closest(".form-group").addClass("has-error");
                    retorno = false;
                } else {
                    $(this).closest(".form-group").removeClass("has-error");
                    retorno = true;
                }
            }); 
    if(retorno){
          document.forms[0].submit();
       }
    }
    
asked by Thiago Gabriel 21.06.2017 в 19:59
source

4 answers

0

Your problem is just that you are putting retorno = true into else . In the way you did, if the last item with class .required is to have some value, the return value will be true , and its form will be executed.

To get around this, you can set the initial value of return = true and if any field is blank, you change the value to false , and remove retorno = true; from else , like this:

function validarCampos() {
  var retorno = true;
  $(".required").each(function() {
    if ($(this).val() === '' || $(this).val() === null) {
      $(this).closest(".form-group").addClass("has-error");
      retorno = false;
      console.log($(this).val())
    } else {
      $(this).closest(".form-group").removeClass("has-error");
    }
  });
  if (retorno) {
    document.forms[0].submit();
  }
}
.has-error {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="form-group col-md-4">
  <label>Fabricante:</label>
  <select class="form-control mensalidade required">
                        <option selected="selected" disabled="disabled">Selecione Algo</option>
                        <option value="1">algo</option>
                </select>
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Produto:</label>
  <input type="text" placeholder="Produto" id="produto" class="form-control required">
</div>
<div class="form-group col-md-4">
  <label>Modelo:</label>
  <input type="text" placeholder="Modelo" id="modelo" class="form-control required">
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Número de serie:</label>
  <input type="text" placeholder="Numero de serie" id="numeroserie" class="form-control required">
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Tensão:</label>
  <select class="form-control mensalidade required" id="tensao" required="">
                    <option selected="selected" disabled="disabled">Selecione a Tensão</option>
                    <option value="1">110</option>
                    <option value="2">220</option>
                    <option value="3">Bivolt</option>
                </select>
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Versão:</label>
  <input type="text" placeholder="Versão do produto (se houver)" id="versao" class="form-control required">
</div>
<div class="form-group col-md-12">
  <label>Descrição:</label>
  <textarea placeholder="Escreva uma descrição do problema" rows="3" class="form-control required"></textarea>
</div>
<div class="box-footer col-md-12">
  <button class="btn btn-warning" type="button" onclick="validarCampos()">Abrir OS</button>
</div>
    
answered by 21.06.2017 / 20:14
source
0

There is an easier resolution for this situation, like using the required in the component's options, something like this:

<input type="text" placeholder="Modelo" id="modelo" class="form-control" required="required">

Try to put required="required" on inputs that you do not want to be empty.

    
answered by 21.06.2017 в 20:03
0

Whatever your intention, do not forget that any client-side validation can easily be fooled. Validate next to the server together.

There is a plugin called jQuery Validation that can be useful for your case. Visit the official page of the plugin where you will find documentation. Here you can find some examples of how this plugin works.

    
answered by 21.06.2017 в 20:16
0

Here's a way to check the blank fields and alert the ones that are blank:

jQuery(function($){
   $("#validar").click(function(){
       var valor = "";
       var id = ""; 
       $("#cadastro .required").each(function(){
          valor = $(this).val(); 
          if (valor == ""){
             id = $(this).attr('id');
             alert ("Campo "+id+" não preenchdo!");
          }
       });
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><formid="cadastro">

<div class="form-group col-md-4">
  <label>Fabricante:</label>
  <select id="fabricante" class="form-control mensalidade required">
      <option selected="selected" value="">Selecione Algo</option>
      <option value="1">algo</option>
   </select>
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Produto:</label>
  <input type="text" placeholder="Produto" id="produto" class="form-control required">
</div>
<div class="form-group col-md-4">
  <label>Modelo:</label>
  <input type="text" placeholder="Modelo" id="modelo" class="form-control required">
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Número de serie:</label>
  <input type="text" placeholder="Numero de serie" id="numeroserie" class="form-control required">
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Tensão:</label>
  <select class="form-control mensalidade required" id="tensao" required="">
                    <option selected="selected" disabled="disabled">Selecione a Tensão</option>
                    <option value="1">110</option>
                    <option value="2">220</option>
                    <option value="3">Bivolt</option>
                </select>
</div>
<div class="form-group col-md-4">
  <label for="inputNome">Versão:</label>
  <input type="text" placeholder="Versão do produto (se houver)" id="versao" class="form-control required">
</div>
<div class="form-group col-md-12">
  <label>Descrição:</label>
  <textarea id="descricao" placeholder="Escreva uma descrição do problema" rows="3" class="form-control required"></textarea>
</div>
<div class="box-footer col-md-12">
  <button id="validar" class="btn btn-warning" type="button">Abrir OS</button>
</div>


</form>
    
answered by 21.06.2017 в 20:20