Validating a field of type input in function of a select

2

I am working with Codeigniter / Bootstrap and need to validate one field of my form depending on another. I have a select field named Contract, with two possible options (Yes or No) and another input type field called ContractDate. I need that when the YES option is selected in the select, filling in the DataContract field becomes mandatory.

    
asked by anonymous 19.09.2016 / 19:05

2 answers

0

To validate to send entities, make obligatory assigning required to the field ContractDate depending on the value of the select Contract. I would use JQuery:

´$(function(){
    $('#IdContrato').change(function(){
     if($('#IdContrato').val()==='Sim'){
      $('#IdDataContrato').prop('required', true);
     }
    });
});´

You can also do a conditional validation after submitting ( View in manual ) if you are validating in the controller / method . Just create a condition dependent on the value sent within the validation rules of $ this-> form_validation-> run ().

    
20.09.2016 / 16:21
1

I made a basic example, I do not know if it's the best way, but it works.

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script>
    
      function ativarInputDataContrato(){
        var lista = document.getElementById("lista-boolean-contrato");
        var input = document.getElementById("data-contrato");
        if(lista.value == "Sim"){
          input.disabled = false;
          input.required = true;
        }else{
          input.disabled = true;
          input.required = false;
        }
      }
      
      
    </script>
  </head>

  <body>
    <form id="formulario">
      Contrato:
       <select id="lista-boolean-contrato" onchange="ativarInputDataContrato()">
         <option value="Nao">Não</option>
         <option value="Sim">Sim</option>
         
       </select>
       <input id = "data-contrato" type = "date" disabled required="true" />
       <input type = "submit" value = "Enviar"/>
     </form>
  </body>

</html>
    
19.09.2016 / 19:32