Javascript validate earlier date than today

Asked

Viewed 1,489 times

1

I am trying to validate a date field of id 'txtDat', as follows:

I want that if the person informs an earlier date than today, show a alert("Por favor, insira uma data futura."), and if you enter a date greater than 30 days, show the alert("Por favor, insira uma data menor que 30 dias.") also, if not, it follows.

As a base I have this code that I got here in stack overflow to validate larger and smaller 65 years

var data_ano = cad.txtDat.value;
var separa = ~data_ano.indexOf("/") ? "/" : "-";
var data_array = Number(data_ano.split(separa).filter(function(e){
   return e.length == 4;
}));

var este_ano = (new Date()).getFullYear();

if(data_array > este_ano-18 || data_array < este_ano-65){
   alert("É preciso ter 18 anos e menos de 65 anos.");
   return;
}

I tried instead of getfullyear the getday, tried several other things but could not do.

  • https://momentjs.com - Maybe this will help you A lot!

  • And if the date matches today?

  • 1

    Remembering that doing this by Javascript can easily be circumvented. Simply the User changes the system date.

  • @dvd do by php then?

  • @dvd if the date is today all right

  • You can do it for both. In PHP it’s for real.

  • then I will validate it by php anyway

  • @dvd but could you do this function just so I could see how it would look? if I were to use it urgently

Show 3 more comments

1 answer

2


You can check whether the date reported is before the current date or longer than 30 days from the current date:

function validadata(d){
   var data = d.value; // pega o valor do input
   data = data.replace(/\//g, "-"); // substitui eventuais barras (ex. IE) "/" por hífen "-"
   var data_array = data.split("-"); // quebra a data em array
   var dia = data_array[2];
   var mes = data_array[1];
   var ano = data_array[0];

   // para o IE onde será inserido no formato dd/MM/yyyy
   if(data_array[0].length != 4){
      dia = data_array[0];
      mes = data_array[1];
      ano = data_array[2];
   }

   var hoje = new Date();
   var d1 = hoje.getDate();
   var m1 = hoje.getMonth()+1;
   var a1 = hoje.getFullYear();

   var d1 = new Date(a1, m1, d1);
   var d2 = new Date(ano, mes, dia);

   var diff = d2.getTime() - d1.getTime();
   diff = diff / (1000 * 60 * 60 * 24);
   
   if(diff < 0){
      console.log("Data não pode ser anterior ao dia de hoje!");
   }else if(diff > 30){
      console.log("Data não pode ser mais do que 30 dias pra frente!");
   }else{
      console.log("Data válida!");
   }
   
}
<input type="date" id="txtDat" onchange="validadata(this)">

  • Thanks man, I don’t know what my TCC would be without you, you’re the guy! Next week I’ll introduce you.

Browser other questions tagged

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