Validation of Inputs with javascript

Asked

Viewed 903 times

0

Good afternoon, I have a form where I built a function to validate unfilled fields. But when I start to fill some fields and leave some empty ones and click on the send button from 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();
       }
    }
  • Would it only be valid if the field is filled or not? If yes, just use the HTML 'required' attribute.

  • is that I wanted to drop an error message so that this attribute is not functional for me.

4 answers

0

There is an easier resolution to this situation, how to use the required in the component options, similar to this:

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

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

  • I need this function because I will drop error messages like a toastr "Fields not filled".

0


Your problem is just the fact that you’re putting the retorno = true in the else. The way you did, get the last item with the class .required if you have any value, the return value will be true, and your form will run.

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

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>
<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>

  • 1

    There are some ways to improve its function, but as it was not the focus of the question, I did not modify.

  • 1

    Actually there are still a few things I’ll include. But I checked and the feedback thing worked perfectly!

0

Whatever your intention with this, do not forget that any validation next to the client can be easily circumvented. Validate next to the server together.

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

  • This is already being done. Daniel, thank you very much for the recommendation. I will check the plugin.

0

Follow a way to check the blank fields and alert those 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>

<form id="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>

  • But from what I noticed it only alerts inputs, select it is not working.

  • @Thiagogabriel Had forgotten a detail, now yes it is validating all fields of the form.

Browser other questions tagged

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