0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

htmlのinput要素だけでバリデーションを設定する

Posted at

概要

htmlのinput要素だけで簡単にバリデーションを設定する方法をまとめる。

内容

下記のように記載することでhtmlだけでバリデーションチェックをする事ができる。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
  <div>
    <form action="post">
      <div>
        <label for="name">名前(必須チェック)</label>
        <input id="name" type="text" required>
      </div>
      <div>
        <label for="email">メールアドレス(必須 + メールアドレス形式チェック)</label>
        <input id="email" type="email">
      </div>
      <div>
        <label for="username">ユーザー名(必須 + 最小文字列と最大文字列チェック)</label>
        <input type="text" id="username" name="username" minlength="1" maxlength="3" required>
      </div>
      <div>
        <label for="age">年齢(必須 + 数値範囲チェック)</label>
        <input type="number" id="age" name="age" min="18" max="99" required>
      </div>
      <div>
        <label for="zipcode">郵便番号(必須 + 正規表現パターンチェック)</label>
        <input type="text" id="zipcode" name="zipcode" pattern="\d{3}-\d{4}" title="XXX-XXXXの形式で入力してください" required>
      </div>
      <button type="submit">登録</button>
    </form>
  </div>
</body>
</html>

ただし、よくあるフレームワークなどのバリデーションと違い、上位の要素から値をチェックしてバリデーションエラーがあったものだけエラーメッセージを出す。
一括ですべてのフォームの値チェックすることはできないので注意

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?