Limit values for input text

Asked

Viewed 631 times

3

I have two inputs and I need the term input value to be greater than the start input value. Both are text type. Someone could help me ?

<div class="w3-half">
     <label>Data de Início</label>
     <input type="text"  name="data_inicio" class="w3-input w3-border" placeholder="YYYY-MM" maxlength="7" minlength="7" pattern="^\d{4}-\d{2}$" title="Insira o valor no formato solicitado: YYYY-MM" required />
</div>
                            
<div class="w3-half" style="width: 40%">
       <label>Prazo</label>
        <input type="text" name="prazo" class="w3-input w3-border" placeholder="YYYY-MM" maxlength="7" minlength="7" pattern="^\d{4}-\d{2}$" title="Insira o valor no formato solicitado: YYYY-MM" required />
</div>

Inputs

  • It will have to be with javascript. And you should also prevent people from filling the deadline first

3 answers

2

You can assign two variables and a function that solves this:

first of all lack the id attribute in your input

function verificar(){

   //pega o valor preenchido no inicio
      var data_inico = document.getElementById('data_inicio').value;
      
      //pega o ano inicio
      var ano_i = data_inico.substring(0, 4);

     //pega o mes inicio
      var mes_i = data_inico.substring(5, 7);
    
      //pega o valor preenchido no fim
      var data_fim = document.getElementById('data_fim').value;

      //pega o ano fim
      var ano_f = data_fim.substring(0, 4);
      //pega o mes fim
      var mes_f = data_fim.substring(5, 7);
           
      //chama a função que vai verificar pra você
      var ehValido = valida_data(mes_i, ano_i, mes_f, ano_f);

      //a função ira retornar true ou false** dependendo do valor retornado você pode fazer o que quiser com o código por ex:

      if(ehValido){
         alert("prazo maior que inicio");
      }else{
         alert("prazo menor que inicio");
      }  
      
}
       
    //cria a função valida_data
    
    function valida_data(mes_i, ano_i, mes_f, ano_f){
    
      if(ano_i>ano_f) return false;
      
      if(mes_i>=mes_f){
     
        return false;

      }else{
        
        return true;

      }

    }
        
    
<div class="w3-half">
         <label>Data de Início</label>
         <input type="text" id="data_inicio" name="data_inicio" class="w3-input w3-border" placeholder="YYYY-MM" maxlength="7" minlength="7" pattern="^\d{4}-\d{2}$" title="Insira o valor no formato solicitado: YYYY-MM" required value='2000-01' />
    </div>
                                
    <div class="w3-half" style="width: 40%">
           <label>Prazo</label>
            <input type="text" id="data_fim" name="prazo" class="w3-input w3-border" placeholder="YYYY-MM" value='2000-02' maxlength="7" minlength="7" pattern="^\d{4}-\d{2}$" title="Insira o valor no formato solicitado: YYYY-MM" required />
    </div>
    
     <button id="btnVal" onclick="verificar()">
    valida
    </button>

Because javascript "knows" its inputs by their id, unlike a back-end language that "knows" them by the name attribute.

Now you create the javascript script that will do this validation for you. Example I did this working, you can use in your code.

2


You can do this check using Javascript. Just convert the values into arrays and compare numbers. I created an example function for this, but you can do as you like:

function checa(){

   // pego valores dos campos, transformo em array
   // e converto os valores para tipo número (Number)
   var d_ini = document.querySelector("input[name='data_inicio']")
               .value.split("-").map(Number);
   var d_pra = document.querySelector("input[name='prazo']")
               .value.split("-").map(Number);

   // crio as variáveis com os anos e os meses
   var ano_ini = d_ini[0], mes_ini = d_ini[1];
   var ano_pra = d_pra[0], mes_pra = d_pra[1];

   // Aqui na comparação, se um ano for menor que o outro já não vale
   // OU se os anos forem iguais mas o mês for igual ou menor, tb não vale
   if( (ano_pra == ano_ini && mes_pra <= mes_ini) || ano_pra < ano_ini ){
      alert("Prazo deve ser depois do início!");
   }else{
      // aqui foi validado. Prazo é maior que início
      alert("OK!");
   }
}
<div class="w3-half">
     <label>Data de Início</label>
     <input type="text"  name="data_inicio" class="w3-input w3-border" placeholder="YYYY-MM" maxlength="7" minlength="7" pattern="^\d{4}-\d{2}$" title="Insira o valor no formato solicitado: YYYY-MM" required />
</div>
                            
<div class="w3-half" style="width: 40%">
       <label>Prazo</label>
        <input type="text" name="prazo" class="w3-input w3-border" placeholder="YYYY-MM" maxlength="7" minlength="7" pattern="^\d{4}-\d{2}$" title="Insira o valor no formato solicitado: YYYY-MM" required />
</div>
<input type="button" onclick="checa()" value="Checar" />

  • How can I Submit to Else ?

  • <form id="myForm"> <div id="actions" class="Row" style="padding-top: 25px; padding-right: 95px"> <input type="Hidden" value="insert" name="acao" </input> <input type="button" onclick="czech()" class="button-upload" value="Save" name="save" </input> </div> </form>

  • Document.getElementById("myForm"). Submit(); and not working

  • keeps on giving by not sending.. I don’t know why rs

  • keeps giving r

  • @Alexsandercaproni input is an element that does not need to be closed with </input>, it closes itself with /> in the end

Show 2 more comments

1

In this case it is recommended to change the fields to "date" type and it is necessary to use javascript to validate the data and alert in case of error, preventing the deadline date is less than the beginning.

<div class="w3-half">
    <label>Data de Início</label>
    <input type="date" name="data_inicio">
</div>
<div class="w3-half">
    <label>Data de Início</label>
    <input type="text" id="dataInicio" on-change="validarDatas()">
</div>
<div class="w3-half" style="width: 40%">
    <label>Prazo</label>
    <input type="text" id="dataPrazo" on-change="validarDatas()">
</div>
<script>
    function validarDatas(evento) {
        // verificar valor das duas datas e validar/invalidar o campo prazo
    }
</script>

It is a relatively simple code using the <input type="date"> because this has the min and max properties that receive minimum and maximum dates and hence you can add a method in the editing event of the start date field that updates the value of the minimum of the term field, without date input you would have to implement a slightly more complex check and validation with Date parse to compare dates and (in)validate the deadline field.

All of this depends mainly on your use of frameworks or javascript tools.

Browser other questions tagged

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