Dates - Javascript

Asked

Viewed 49 times

1

Hello! I am not able to compare the dates of a user input with today’s date. To be able to return an alert to the user. I made another example and it worked, but this one didn’t. Can anyone see the error(s) (s)?

<script type="text/javascript">

function validarData(){

    var data_entrega = document.getElementById('data_entrega').value;

    var data = new Date(); //obtem data hoje

    var dia     = data.getDate();           // 1-31
    var mes     = data.getMonth();          // 0-11 (zero=janeiro)
    var ano4    = data.getFullYear();       // 4 dígitos



    var data_hoje = dia + '/' + (mes+1) + '/' + ano4; //formatação igual ao input do usuário


    var sete_dias = data_hoje + 7; // regra 7 dias (chroma)



    if(data_entrega < data_hoje){

        alert("Atenção! Data de entrega já passou!");


    }else if(data_entrega > sete_dias){

        alert("Atenção! Data de entrega ultrapassa 7 dias!");


    }


}
    

</script>
    <input type="date" name="data_entrega" id="data_entrega" class="form-control" value="" required="" onblur="validarData()">

Thank you!

  • Thank you for answering. So, I’m bringing for the Onblur event in input, I take the value of it ( var data_delivery = Document.getElementById('data_delivery').value;). You have to do something else?

  • I got it solved! Thanks anyway! Had to format the user date.

1 answer

0


The format of data_hoje is wrong about the date captured on input.

It is necessary to treat the values of day and month to have 2 digits if they only have 1 (as a month from January to September) and days from 1 to 9, to have the standard YYYY/MM/DD.

See working:

function validarData(){

    var data_entrega = document.getElementById('data_entrega').value;
    
    var data_entrega_array = data_entrega.split( data_entrega.indexOf("/") != -1 ? "/" : "-" );
    
    if(data_entrega_array[2].length == 4){
       data_entrega = data_entrega_array[2]+"-"+data_entrega_array[1]+"-"+data_entrega_array[0];
    }

    var data = new Date(); //obtem data hoje

    var dia     = data.getDate();           // 1-31
    var mes     = data.getMonth()+1;          // 0-11 (zero=janeiro)
    var ano4    = data.getFullYear();       // 4 dígitos

    if(dia.toString().length == 1) dia = '0'+dia;
    if(mes.toString().length == 1) mes = '0'+mes;

    var data_hoje = ano4 + '-' + mes + '-' + dia; //formatação igual ao input do usuário


    var sete_dias = ano4 + '-' + mes + '-' + parseInt(dia+7); // regra 7 dias (chroma)

    if(data_entrega < data_hoje){

        alert("Atenção! Data de entrega já passou!");


    }else if(data_entrega > sete_dias){

        alert("Atenção! Data de entrega ultrapassa 7 dias!");


    }


}
<input type="date" name="data_entrega" id="data_entrega" class="form-control" value="" required="" onblur="validarData()">

Browser other questions tagged

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