【问题标题】:validating dates using html5 and thymeleaf使用 html5 和 thymeleaf 验证日期
【发布时间】:2020-11-01 06:17:43
【问题描述】:

我有一个接受日期输入的表单。我想验证用户没有选择未来的日期。我知道我可以在 html 中放置最小值和最大值,但我看到的唯一示例日期是硬编码的,所以我尝试通过将 currentDate 的值添加到模型中来将其传递给 html

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>

但我确实接受了未来的日期,而不是我想要的。有什么建议吗?

【问题讨论】:

    标签: java html date thymeleaf


    【解决方案1】:

    您可以通过 Javascript 以正确的格式获取当前日期并使用它来设置日期输入的maxvalue。像这样的:

    
    $(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);
    });
    
    

    【讨论】:

    • 谢谢,效果很好。您仍然知道为什么我不能使用我在 java 代码中得到的日期吗?
    • @kalina199 可能是因为您的 currentDate 模型属性的类型为 LocalDate。尝试将其转换为字符串并将字符串存储在模型中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2022-01-11
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    相关资源
    最近更新 更多