7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

input type="email" の値の書式

Posted at

フォームの入力欄で type="email" を使うと、入力値がメールアドレスとして正しいかどうかをブラウザーに判別してもらうことができます。

<input type="email" name="email">

そのメールアドレスの書式は具体的にどんなものかというと、HTML5の仕様書に正規表現で提示されています。

The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

この正規表現には1つ問題がありまして、それは taro@hogehoge のように . を含まないドメイン名のアドレスはアリであることです。hogehoge はドメイン名の書式としてアリなので、そりゃそうです。

といっても、普通は taro@hogehoge は禁止したいですよね。それには、次の正規表現を使います。最後の *+ に変えるだけ。

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/

これを inputpattern属性に指定すると、taro@hogehoge が送信できないようにできます。

<input type="email" name="email"
  pattern="^[a-zA-Z0-9.!#$&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$" >
7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?