0
0

Spring Thymeleaf type="date"で過去の日付を選択できないようにする方法 備忘録#3

Posted at

type="date"で、過去の日付を選択できないようにする方法

初めに

今回は、WEBサイト開発の中で、「予約時に過去の日付は選択させたくない!!」と思い調べても見つからず、周囲の賢い方に教えてもらったので、記録として残したいと思います。

###画像イメージ

スクリーンショット 2024-06-13 22.43.08.png

↑このように、カレンダーで選択画面が表示され、過去の日付を押そうとすると現在の日付になります。
※Windowsでは、過去の日付が全てグレー色になって、選択できないようになります。

このように、日付を選択させないやり方は、thymeleafの機能だけで行うことができます!

###HTML

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
  <meta charset="UTF-8">
  <title>予約</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
    crossorigin="anonymous"></script>
</head>

<body>

  <h1 class="text-center mt-5">予約ページ</h1>

  <form action="/reservation" method="post">
    <div class="w-50 mx-auto">

      <table border="1" class="table">
        <tr>
          <th>名前</th>
          <td><input type="text" name="name" placeholder="名前"></td>
        </tr>
        <tr>
          <th>日付</th>
+          <td><input type="date" name="date" th:min="${#dates.format(#dates.createNow(), 'yyyy-MM-dd')}"></td>
        </tr>
      </table>
    <div class="text-center"> 
    
      <button class="btn btn-primary" type="submit" onclick="return confirm('本当に移動しますか?');">予約</button>
    </div>
    </div>
  </form>
</body>

</html>

緑の線が引いてある行のように、
th:min="${#dates.format(#dates.createNow(), 'yyyy-MM-dd')}"
とすることで、過去の日付が選択されないようになります。

また、minは最小値という意味なので、maxにすると、逆に未来の日付を選択できないようにします。

これはthymeleafの機能なので、Springの場合は、Controllerに何も書かなくてもエラーチェックをすることができるのです!!

以上で今回の備忘録を終わります!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0