Skip to content
Advertisement

Validate select field with valid using chosen-select

When validating the form, using chosen-select does not validate the selects, but removing ochosen-select already works. I show the example:

$("#validate").on("click",function(){
    if(!$(".alerta").valid());
  });
  
  $(".alerta").validate({
      messages: {
        Tipo: "Tipo de alerta obrigatório",
        Prioridade: {
              required: "Prioridade obrigatório"
          }
      }
  });
  
  
$(".chosen-select").chosen({
    disable_search_threshold: 5,
    no_results_text: "Sem resultados",
      placeholder_text_multiple: "Selecione opções",
    width: "100%"
}); 
 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

<form method="POST" class="row g-3 alerta">
  <div class="col-md-4">
    <label for="Tipo" class="form-label">TIPO DE ALERTA <span style="color: red;">*</span></label>
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option></option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>
  </div>
  
  <div class="col-md-4">
    <label for="Tipo" class="form-label">Prioridade <span style="color: red;">*</span></label>
    <select class="form-select" name="Prioridade" id="Prioridade" required>
    <option></option>
    <option value="1">Prioridade</option>
    <option value="2">Prioridade1</option>
    </select>
  </div>
  <div class="col-12">
    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" id="validate"> Enviar <i class="metismenu-icon pe-7s-paper-plane"></i></button>
  </div>
</form>

In the select in which I use chosen-select, there is no value selected, but it does not show the message to the user as the field is mandatory.

Advertisement

Answer

Chosen-select adds visibility:hidden attribute in select box.

You have to validate chosen-select forcefully.

$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })

Please add above line just before (".alerta").validate() method.

Advertisement