|
| 1 | +--- |
| 2 | +title: AstroページでHTMLフォームを構築する |
| 3 | +description: フロントマターで送信を処理しながら、HTMLフォームを構築する方法を学びます。 |
| 4 | +i18nReady: true |
| 5 | +type: recipe |
| 6 | +--- |
| 7 | +import { Steps } from '@astrojs/starlight/components'; |
| 8 | + |
| 9 | +オンデマンドでレンダリングされるAstroページは、フォームの表示と処理の両方に対応できます。このレシピでは、標準的なHTMLフォームでデータをサーバーへ送信します。フロントマターのスクリプトでサーバー側の処理を行い、クライアントへはJavaScriptを送信しません。 |
| 10 | + |
| 11 | +:::tip[Astro Actionsでフォームを構築する] |
| 12 | +Astro v4.15ではActionsが追加され、基本的なHTMLフォームよりも、データ検証や送信結果に基づくUI更新などの利点が得られます。こちらの方法を使いたい場合は、[Actionsガイド](/ja/guides/actions/)をご覧ください。 |
| 13 | +::: |
| 14 | + |
| 15 | +## 前提条件 |
| 16 | +- [サーバーアダプター](/ja/guides/on-demand-rendering/#サーバーアダプター)をインストールしたAstroプロジェクト。 |
| 17 | + |
| 18 | +## レシピ |
| 19 | + |
| 20 | +<Steps> |
| 21 | +1. フォーム本体とハンドリングコードを含む`.astro`ページを作成(または特定)します。たとえば、登録ページを追加します。 |
| 22 | + |
| 23 | + |
| 24 | + ```astro title="src/pages/register.astro" |
| 25 | + --- |
| 26 | + --- |
| 27 | + <h1>Register</h1> |
| 28 | + ``` |
| 29 | + |
| 30 | +2. ページに`<form>`タグと各種入力フィールドを追加します。各入力には、その値の意味を表す`name`属性を付けます。 |
| 31 | + |
| 32 | + |
| 33 | + 必ず送信用の`<button>`または`<input type="submit">`要素を含めます。 |
| 34 | + |
| 35 | + ```astro title="src/pages/register.astro" |
| 36 | + --- |
| 37 | + --- |
| 38 | + <h1>Register</h1> |
| 39 | + <form> |
| 40 | + <label> |
| 41 | + Username: |
| 42 | + <input type="text" name="username" /> |
| 43 | + </label> |
| 44 | + <label> |
| 45 | + Email: |
| 46 | + <input type="email" name="email" /> |
| 47 | + </label> |
| 48 | + <label> |
| 49 | + Password: |
| 50 | + <input type="password" name="password" /> |
| 51 | + </label> |
| 52 | + <button>Submit</button> |
| 53 | + </form> |
| 54 | + ``` |
| 55 | + |
| 56 | +3. [バリデーション属性](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#using_built-in_form_validation)を使い、JavaScriptが無効でも動作する基本的なクライアントサイド検証を追加します。 |
| 57 | + |
| 58 | + |
| 59 | + この例では、 |
| 60 | + - `required`は、入力が埋まるまで送信を防ぎます。 |
| 61 | + - `minlength`は、入力文字数の下限を設定します。 |
| 62 | + - `type="email"`は、有効なメール形式のみを受け付ける検証を導入します。 |
| 63 | + |
| 64 | + ```astro title="src/pages/register.astro" |
| 65 | + --- |
| 66 | + --- |
| 67 | + <h1>Register</h1> |
| 68 | + <form> |
| 69 | + <label> |
| 70 | + Username: |
| 71 | + <input type="text" name="username" required /> |
| 72 | + </label> |
| 73 | + <label> |
| 74 | + Email: |
| 75 | + <input type="email" name="email" required /> |
| 76 | + </label> |
| 77 | + <label> |
| 78 | + Password: |
| 79 | + <input type="password" name="password" required minlength="6" /> |
| 80 | + </label> |
| 81 | + <button>Submit</button> |
| 82 | + </form> |
| 83 | + ``` |
| 84 | + |
| 85 | + :::tip |
| 86 | + 複数フィールドを参照する独自の検証は、`<script>`タグと[Constraint Validation API](https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation#complex_constraints_using_the_constraint_validation_api)で追加できます。 |
| 87 | + |
| 88 | + より複雑な検証ロジックを簡単に記述するには、[フロントエンドフレームワーク](/ja/guides/framework-components/)と、[React Hook Form](https://react-hook-form.com/)や[Felte](https://felte.dev/)のようなフォームライブラリを使う方法もあります。 |
| 89 | + ::: |
| 90 | + |
| 91 | +4. フォーム送信によりブラウザーは同じページを再リクエストします。データ転送方式をURLパラメーターではなく`Request`ボディで送るために、フォームの`method`を`POST`に変更します。 |
| 92 | + |
| 93 | + |
| 94 | + ```astro title="src/pages/register.astro" 'method="POST"' |
| 95 | + --- |
| 96 | + --- |
| 97 | + <h1>Register</h1> |
| 98 | + <form method="POST"> |
| 99 | + <label> |
| 100 | + Username: |
| 101 | + <input type="text" name="username" required /> |
| 102 | + </label> |
| 103 | + <label> |
| 104 | + Email: |
| 105 | + <input type="email" name="email" required /> |
| 106 | + </label> |
| 107 | + <label> |
| 108 | + Password: |
| 109 | + <input type="password" name="password" required minlength="6" /> |
| 110 | + </label> |
| 111 | + <button>Submit</button> |
| 112 | + </form> |
| 113 | + ``` |
| 114 | + |
| 115 | +5. フロントマターで`POST`メソッドを判定し、`Astro.request.formData()`でフォームデータへアクセスします。`POST`がフォーム送信でない場合など`formData`が不正なケースに備え、`try ... catch`で囲みます。 |
| 116 | + |
| 117 | + |
| 118 | + ```astro title="src/pages/register.astro" ins={2-16} "Astro.request.formData()" |
| 119 | + --- |
| 120 | + export const prerender = false; // 「server」モードでは不要です |
| 121 | + |
| 122 | + if (Astro.request.method === "POST") { |
| 123 | + try { |
| 124 | + const data = await Astro.request.formData(); |
| 125 | + const name = data.get("username"); |
| 126 | + const email = data.get("email"); |
| 127 | + const password = data.get("password"); |
| 128 | + // 取得したデータを処理する |
| 129 | + } catch (error) { |
| 130 | + if (error instanceof Error) { |
| 131 | + console.error(error.message); |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + --- |
| 136 | + <h1>Register</h1> |
| 137 | + <form method="POST"> |
| 138 | + <label> |
| 139 | + Username: |
| 140 | + <input type="text" name="username" required /> |
| 141 | + </label> |
| 142 | + <label> |
| 143 | + Email: |
| 144 | + <input type="email" name="email" required /> |
| 145 | + </label> |
| 146 | + <label> |
| 147 | + Password: |
| 148 | + <input type="password" name="password" required minlength="6" /> |
| 149 | + </label> |
| 150 | + <button>Submit</button> |
| 151 | + </form> |
| 152 | + ``` |
| 153 | + |
| 154 | +6. サーバー側でフォームデータを検証します。これは、悪意のある送信を防ぐためにクライアント側と同じ検証を含めるべきですし、フォーム検証を持たないレガシーブラウザーへの対応にも役立ちます。 |
| 155 | + |
| 156 | + |
| 157 | + また、クライアント側では行えない検証も含められます。たとえば、メールアドレスがすでにデータベースに存在するかどうかを確認します。 |
| 158 | + |
| 159 | + エラーメッセージは`errors`オブジェクトに保持し、テンプレートで参照することでクライアントへ返すことができます。 |
| 160 | + |
| 161 | + ```astro title="src/pages/register.astro" ins={7, 14-24, 43, 48, 53} |
| 162 | + --- |
| 163 | + export const prerender = false; // Not needed in 'server' mode |
| 164 | + |
| 165 | + import { isRegistered, registerUser } from "../../data/users" |
| 166 | + import { isValidEmail } from "../../utils/isValidEmail"; |
| 167 | +
|
| 168 | + const errors = { username: "", email: "", password: "" }; |
| 169 | + if (Astro.request.method === "POST") { |
| 170 | + try { |
| 171 | + const data = await Astro.request.formData(); |
| 172 | + const name = data.get("username"); |
| 173 | + const email = data.get("email"); |
| 174 | + const password = data.get("password"); |
| 175 | + if (typeof name !== "string" || name.length < 1) { |
| 176 | + errors.username += "Please enter a username. "; |
| 177 | + } |
| 178 | + if (typeof email !== "string" || !isValidEmail(email)) { |
| 179 | + errors.email += "Email is not valid. "; |
| 180 | + } else if (await isRegistered(email)) { |
| 181 | + errors.email += "Email is already registered. "; |
| 182 | + } |
| 183 | + if (typeof password !== "string" || password.length < 6) { |
| 184 | + errors.password += "Password must be at least 6 characters. "; |
| 185 | + } |
| 186 | + const hasErrors = Object.values(errors).some(msg => msg) |
| 187 | + if (!hasErrors) { |
| 188 | + await registerUser({name, email, password}); |
| 189 | + return Astro.redirect("/login"); |
| 190 | + } |
| 191 | + } catch (error) { |
| 192 | + if (error instanceof Error) { |
| 193 | + console.error(error.message); |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | + --- |
| 198 | + <h1>Register</h1> |
| 199 | + <form method="POST"> |
| 200 | + <label> |
| 201 | + Username: |
| 202 | + <input type="text" name="username" /> |
| 203 | + </label> |
| 204 | + {errors.username && <p>{errors.username}</p>} |
| 205 | + <label> |
| 206 | + Email: |
| 207 | + <input type="email" name="email" required /> |
| 208 | + </label> |
| 209 | + {errors.email && <p>{errors.email}</p>} |
| 210 | + <label> |
| 211 | + Password: |
| 212 | + <input type="password" name="password" required minlength="6" /> |
| 213 | + </label> |
| 214 | + {errors.password && <p>{errors.password}</p>} |
| 215 | + <button>Register</button> |
| 216 | + </form> |
| 217 | + ``` |
| 218 | +</Steps> |
0 commit comments