Do not allow Retroactive date in the Date type field

Asked

Viewed 1,128 times

1

The date field cannot allow Retroactive dates. need the script to recognize the current date and not allow earlier dates.

<div class="col-sm-4">
    <label for="ultimoDiaTrab" class="control-label">Último dia a ser trabalhado:</label>
    <input type="date" id="ultimoDiaTrab" name="ultimoDiaTrab" class="form-control" disabled />                         
</div>

2 answers

2


You can do it like this:

var input = document.getElementById('ultimoDiaTrab');
input.addEventListener('change', function() {
  var agora = new Date();
  var escolhida = new Date(this.value);
  if (escolhida < agora) this.value = [agora.getFullYear(), agora.getMonth() + 1, agora.getDate()].map(v => v < 10 ? '0' + v : v).join('-');
});
<div class="col-sm-4">
  <label for="ultimoDiaTrab" class="control-label">Último dia a ser trabalhado:</label>
  <input type="date" id="ultimoDiaTrab" name="ultimoDiaTrab" class="form-control" />
</div>

In this case this.value = [agora.getFullYear(), agora.getMonth() + 1, agora.getDate()].map(v => v < 10 ? '0' + v : v).join('-'); reset the chosen date to the current date, if you just want to delete you can do this.value = '';

  • Thus, it fixes the current date. I need it to recognize the current date and not allow old dates. ie, it may have future dates. In the case that passed me, he does not allow. Thank you, Sergio!!

  • @Karinapinheiro my example allows future dates.

  • 1

    Sergio, it did work! It was my mistake here. A question, what if it was to appear a warning instead of replacing the date? type " enter a Future date" as soon as the field has been filled in.

0

I got it this way

    <input type="date" max={new Date().getFullYear() + '-' + String(new Date().getMonth() + 1).padStart(2, '0') + '-' + new Date().getDate()} name="stockDate" id="dateMax" />        

Using the max property, you can establish the highest value, and through the functions, you can get the current date

Obs: this code works in React Native, you may have to make some changes if it is html.

Browser other questions tagged

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