validating dates using html5 and thymeleaf

Viewed 98

I have a form that takes a date input. I want to validate that the user isnt picking a future date. I know that there is min and max which I can place in the html, but the only examples I saw the date is hardcoded, so I tried using passing the value of the currentDate to the html by adding it to the Model

model.addAttribute("currentDate", LocalDate.now());



<input type="date" max="${currentDate}" data-th-max="${currentDate}" id="yearOfRegistration" name="yearOfRegistration"/>
                    <label class="error" th:errors="${initialRequestDTO.yearOfRegistration}"></label>

I do however the form accepts future dates, not as I intended it. Any suggestions?

1 Answers

You can do it through Javascript by getting the current date in the correct format and using it to set the maxvalue of the date input. Something like this:


$(function() {
  var currentDate = new Date();
  var month = currentDate.getMonth() + 1;
  var day = currentDate.getDate();
  var year = currentDate.getFullYear();

  if (month < 10) {
    month = '0' + month.toString();
  }

  if (day < 10) {
    day = '0' + day.toString();
  }

  var maxDate = year + '-' + month + '-' + day;
  $('#yearOfRegistration').attr('max', maxDate);
});

Related