--- title: ': 入力欄 (フォーム入力) 要素' slug: Web/HTML/Element/input tags: - Element - Forms - HTML - HTML input tag - HTML フォーム - 'HTML:フローコンテンツ' - 'HTML:対話型コンテンツ' - 'HTML:記述コンテンツ' - Reference - Web - ウェブ - データ入力 - フォーム - 要素 translation_of: Web/HTML/Element/input ---
{{HTMLRef}}

HTML の <input> 要素は、ユーザーからデータを受け取るための、ウェブベースのフォーム用の対話的なコントロールを作成するために使用します。端末と{{Glossary("user agent", "ユーザーエージェント")}}によりますが、広範に渡る種類のデータ入力やコントロールウィジェットが利用できます。 <input> 要素は入力型と属性の組み合わせの数が非常に多いため、 HTML の中で最も強力かつ最も複雑な要素の一つです。

{{EmbedInteractiveExample("pages/tabbed/input-text.html", "tabbed-shorter")}}

<input> の型

<input> の動作は {{htmlattrxref("type", "input")}} 属性の値に応じて大きく異なりますので、個別のリファレンスページでさまざまな型を扱っています。この属性を指定しない場合の既定の型は text です。

利用可能な型は次の通りです。

説明 基本的な例 仕様書
{{HTMLElement("input/button", "button")}} プッシュボタンで、既定の動作を持たず、 {{anch('htmlattrdefvalue', 'value')}} 属性の値 (既定では空) を表示します。 {{EmbedLiveSample("examplebutton",200,55,"","", "nobutton")}}
{{HTMLElement("input/checkbox", "checkbox")}} チェックボックスで、選択または未選択のうちひとつの値をとることができます。 {{EmbedLiveSample("examplecheckbox",200,55,"","", "nobutton")}}
{{HTMLElement("input/color", "color")}} 色を指定するためのコントロールです。対応しているブラウザーでは、アクティブになったときにカラーピッカーが開きます。 {{EmbedLiveSample("examplecolor",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/date", "date")}} 日付 (時刻を除く年、月、日) を入力するためのコントロールです。対応しているブラウザーでは、アクティブになったときに日付ピッカーまたは年月日の数値のホイールが開きます。 {{EmbedLiveSample("exampledate",200,55,"","", "nobutton")}}   {{HTMLVersionInline("5")}}
{{HTMLElement("input/datetime-local", "datetime-local")}} タイムゾーン情報がない日付と時刻を入力するためのコントロールです。対応しているブラウザーでは、アクティブになったときに日付ピッカーまたは日付および時刻部分の数値のホイールが開きます。 {{EmbedLiveSample("exampledtl",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/email", "email")}} 電子メールアドレスを編集するための欄です。 text 入力欄のように見えますが、対応しているブラウザーや動的なキーボードのある端末では、入力値を検証したり、関連するキーボードを表示したりします。 {{EmbedLiveSample("exampleemail",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/file", "file")}} ユーザーがファイルを選択するコントロールです。 {{anch('htmlattrdefaccept', 'accept')}} 属性を使用して、コントロールが選択することができるファイル形式を定義することができます。 {{EmbedLiveSample("examplefile",'100%',55,"","", "nobutton")}}
{{HTMLElement("input/hidden", "hidden")}} 表示されないコントロールですが、その値はサーバーに送信されます。隣の列には例がありますが、非表示です。
{{HTMLElement("input/image", "image")}} グラフィックの submit ボタンです。 src 属性で定義された画像を表示します。 {{anch('htmlattrdefalt', 'alt')}} 属性は {{anch('htmlattrdefsrc', 'src')}} の画像が見つからないときに表示されます。 {{EmbedLiveSample("exampleimage",200,55,"","", "nobutton")}}
{{HTMLElement("input/month", "month")}} タイムゾーン情報がない年と月を入力するためのコントロールです。 {{EmbedLiveSample("examplemonth",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/number", "number")}} 数値を入力するためのコントロールです。対応していればスピナーを表示し、既定の検証を追加します。動的キーボードを持つ一部の端末では、テンキーを表示します。 {{EmbedLiveSample("examplenumber",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/password", "password")}} 入力値を隠す1行テキストフィールド。サイトが安全ではない場合はユーザーに警告します。 {{EmbedLiveSample("examplepassword",200,55,"","", "nobutton")}}
{{HTMLElement("input/radio", "radio")}} ラジオボタンで、同じ {{anch('htmlattrdefname', 'name')}} の値を持つ複数の選択肢から一つの値を選択することができます。 {{EmbedLiveSample("exampleradio",200,55,"","", "nobutton")}}
{{HTMLElement("input/range", "range")}} 厳密な値であることが重要ではない数値を入力するためのコントロールです。範囲のウィジェットを表示し、既定では中央の値になります。 {{anch('htmlattrdefmin', 'min')}} と {{anch('htmlattrdefmax', 'max')}} の組み合わせで、受け入れる値の範囲を定義することができます。 {{EmbedLiveSample("examplerange",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/reset", "reset")}} フォームのコントロールを既定値に初期化するボタンです。推奨しません。 {{EmbedLiveSample("examplereset",200,55,"","", "nobutton")}}
{{HTMLElement("input/search", "search")}} 検索文字列を入力するための単一行のテキスト欄です。入力値から改行が自動的に取り除かれます。対応しているブラウザーでは、入力欄を初期化するための削除アイコンが表示されることがあり、欄の内容を消去するために使用することができます。 Displays a search icon instead of enter key on some devices with dynamic keypads. {{EmbedLiveSample("examplesearch",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/submit", "submit")}} フォームを送信するボタンです。 {{EmbedLiveSample("examplesubmit",200,55,"","", "nobutton")}}
{{HTMLElement("input/tel", "tel")}} 電話番号を入力するためのコントロールです。動的なテンキーを備えた一部の機器では、電話用のテンキーを表示します。 {{EmbedLiveSample("exampletel",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/text", "text")}} 既定値です。単一行の入力欄です。改行は自動的に入力値から取り除かれます。 {{EmbedLiveSample("exampletext",200,55,"","", "nobutton")}}
{{HTMLElement("input/time", "time")}} タイムゾーン情報がない時刻を入力するためのコントロールです。 {{EmbedLiveSample("exampletime",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/url", "url")}} URL 入力するための入力欄です。 text 入力欄のように見えますが、対応しているブラウザーや動的なキーボードのある端末では、入力値を検証したり、関連するキーボードを表示したりします。 {{EmbedLiveSample("exampleurl",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
{{HTMLElement("input/week", "week")}} 年と週番号で構成される日付を入力するためのコントロールです。週番号はタイムゾーンを伴いません。 {{EmbedLiveSample("exampleweek",200,55,"","", "nobutton")}} {{HTMLVersionInline("5")}}
廃止された値
{{HTMLElement("input/datetime", "datetime")}} {{deprecated_inline}} {{obsolete_inline}} UTC タイムゾーンに基づく日付と時刻 (時、分、秒、秒の端数) を入力するためのコントロールです。 {{EmbedLiveSample("exampledatetime",200,75,"","", "nobutton")}} {{HTMLVersionInline("5")}}

属性

<input> 要素は属性があるためたいへん強力です。上記の例で説明している {{htmlattrxref("type", "input")}} 属性が最も重要です。すべての <input> 要素が、 {{domxref("HTMLInputElement")}} インターフェイスに基づいているため、、技術的にはまったく同じ属性を共有しています。しかし実際には、ほとんどの属性は一部の特定の入力型にのみ影響を与えます。さらに、属性によっては入力欄に影響を及ぼす方法が入力型によって異なり、入力型によって異なる方法で影響を与えることがあります。

この節では、すべての属性に簡単な説明を書いた一覧表を示します。その後で、それぞれの属性がどの入力型に関連付けられているか、より詳細に説明された一覧を示します。ほとんど、またはすべての入力型に共通する属性については、以下でより詳細に定義します。特定の入力型に固有の属性、またはすべての入力型に共通するが、特定の入力型で使用されたときに特別な動作をする属性は、それぞれの型のページで示します。この要素はグローバル属性を含みます。 <input> に関連して特に重要な属性は強調表示されています。

{{htmlelement('input')}} 要素の属性で、グローバル HTML 属性を含むもの
属性 説明
{{anch('htmlattrdefaccept', 'accept')}} file ファイルアップロードコントロールで期待されるファイル形式のヒント
{{anch('htmlattrdefalt', 'alt')}} image image 型の alt 属性です。アクセシビリティのために必要です。
{{anch('htmlattrdefautocomplete', 'autocomplete')}} すべて フォームの自動補完機能のためのヒント
{{anch('htmlattrdefautofocus', 'autofocus')}} すべて ページが読み込まれたときに、自動的にそのフォームコントロールにフォーカスを設定する
{{anch('htmlattrdefcapture', 'capture')}} file ファイルアップロードコントロールのメディアキャプチャのインプットメソッド
{{anch('htmlattrdefchecked', 'checked')}} radio, checkbox コマンドやコントロールがチェックされているか
{{anch('htmlattrdefdirname', 'dirname')}} text, search フォーム送信時に要素の方向性を送信するために使用するフォームフィールドの名前です。
{{anch('htmlattrdefdisabled', 'disabled')}} すべて コントロールが無効であるかどうか
{{anch('htmlattrdefform', 'form')}} すべて コントロールを form 要素に関連付ける
{{anch('htmlattrdefformaction', 'formaction')}} image, submit フォームの送信に使用する URL
{{anch('htmlattrdefformenctype', 'formenctype')}} image, submit フォームの送信に使用するデータセットのエンコード種別
{{anch('htmlattrdefformmethod', 'formmethod')}} image, submit フォームの送信に使用する HTTP メソッド
{{anch('htmlattrdefformnovalidate', 'formnovalidate')}} image, submit フォームの送信でフォームの検証をバイパス
{{anch('htmlattrdefformtarget', 'formtarget')}} image, submit フォーム送信に使用する閲覧コンテキスト
{{anch('htmlattrdefheight', 'height')}} image {{htmlelement('img')}} の height 属性と同じで、垂直の高さ
{{anch('htmlattrdeflist', 'list')}} ほぼすべて 自動補完オプションの入った {{htmlelement('datalist')}} の id 属性の値
{{anch('htmlattrdefmax', 'max')}} 数値型 最大値
{{anch('htmlattrdefmaxlength', 'maxlength')}} password, search, tel, text, url value の最大長 (文字数)
{{anch('htmlattrdefmin', 'min')}} 数値型 最小値
{{anch('htmlattrdefminlength', 'minlength')}} password, search, tel, text, url value の最小長 (文字数)
{{anch('htmlattrdefmultiple', 'multiple')}} email, file 論理属性。複数の値を許可するかどうか
{{anch('htmlattrdefname', 'name')}} すべて 入力欄コントロールの名前。名前/値の組の部分としてフォームと一緒に送信される
{{anch('htmlattrdefpattern', 'pattern')}} password, text, tel value が一致すると妥当となるパターン
{{anch('htmlattrdefplaceholder', 'placeholder')}} password, search, tel, text, url フォームコントロールが空の時にフォームコントロール内に表示される内容
readonly ほぼすべて 論理属性。値が編集できない
required ほぼすべて 論理属性。フォームが送信できるようにするためには値が必要
{{anch('htmlattrdefsize', 'size')}} email, password, tel, text コントロールの大きさ
{{anch('htmlattrdefsrc', 'src')}} image {{htmlelement('img')}} の src 属性と同じで、画像リソースのアドレス
{{anch('htmlattrdefstep', 'step')}} numeric types 有効な増分
{{anch('htmlattrdeftype', 'type')}} all 入力フォームコントロールの型
{{anch('htmlattrdefvalue', 'value')}} all このフォームコントロールの現在の値。名前/値の組の部分としてフォームと一緒に送信される
{{anch('htmlattrdefwidth', 'width')}} image {{htmlelement('img')}} の width 属性と同じ

標準属性の説明に続いて、いくつかの追加の非標準属性を列挙します。

個々の属性

{{htmlattrdef("accept")}}

file 入力型に対してのみ有効です。 accept 属性は file アップロードコントロールの中でどのファイル形式が選択可能であるかを定義します。 {{HTMLElement("input/file", "file")}} 入力型を参照してください。

{{htmlattrdef("alt")}}

image ボタンに対してのみ有効です。 alt 属性は画像の代替テキストを提供し、 src の画像が存在しないか、または読み込みに失敗した場合にこの属性の値を表示します。 {{HTMLElement("input/image", "image")}} 入力型を参照してください。

{{htmlattrdef("autocomplete")}}

(論理属性ではありません!) autocomplete 属性は空白区切りの文字列の値を取り、指定された場合は、入力欄が提供する自動補完機能の種類を示します。自動補完のよくある実装は、以前同じ入力欄に入力された値を単に再呼び出しするものですが、もっと複雑な自動補完もあり得ます。例えば、ブラウザーが端末の連絡先リストと連携して、 email 入力欄でメールアドレスを自動補完したりする可能性もあります。許可されている値はautocomplete 属性の値を参照してください。

autocomplete 属性は hidden, text, search, url, tel, email, date, month, week, time, datetime-local, number, range, color, password で有効です。この属性は数値またはテキストデータを返さない入力型では効果がなく、 checkbox, radio, file とすべてのボタン型を除いたすべての入力型で有効になります。

詳しい情報については HTML の autocomplete 属性を参照してください。パスワードセキュリティに関する情報や、 autocompletehidden に対して他の入力型とどう異なるのかについての情報があります。

{{htmlattrdef("autofocus")}}

論理属性で、指定された場合は、ページの読み込みが完了したとき (またはその要素を含む {{HTMLElement("dialog")}} が表示されたとき) に、自動的にその入力欄がフォーカスを持つことを示します。

注: autofocus 属性がついた要素は、 {{domxref("DOMContentLoaded")}} イベントが発生する前にフォーカスを得ることがあります。

文書中で一つの要素だけが autofocus 属性を持つことができます。複数の要素に付けた場合は、最初にこの属性を持つ要素がフォーカスを受け取ります。

autofocushidden 型の入力欄にはフォーカスを受け取ることができないため、使用することができません。

警告: フォームコントロールに自動的にフォーカスを与えると、読み上げ技術を利用している視覚障碍者を混乱させる可能性があります。 autofocus が割り当てられると、読み上げソフトは予告なしにフォームコントロールにその人を「テレポート」させることになるからです。

autofocus 属性を適用する際には、アクセシビリティを慎重に検討してください。フォームコントロールにフォーカスを自動的に設定すると、読み込み時にページのスクロールが発生します。フォーカスを与えると、一部のタッチ端末では動的なキーボードを表示させることにもなります。読み上げソフトはフォーカスを受けているフォームコントロールのラベルをアナウンスする一方、ラベルよりも前は何もアナウンスしませんし、小さな端末を使用している視力のあるユーザーは、同様に先行するコンテンツによって作成された文脈を見逃してしまいます。

{{htmlattrdef("capture")}}

HTML Media Capture 仕様書で導入され、 file 入力型に対してのみ有効です。 capture 属性は、どのメディア (マイク、ビデオ、カメラ) を使用して新しいファイルをキャプチャし、対応するシナリオで file アップロードコントロールを使用してアップロードするかを定義します。 {{HTMLElement("input/file", "file")}} 入力型を参照してください。

{{htmlattrdef("checked")}}

radio 型と checkbox 型の両方で有効で、 checked は論理属性です。 radio 型に存在した場合、そのラジオボタンが同じ名前のラジオボタンのグループの中で現在選択されているものであることを示します。 checkbox 型に存在した場合、 (ページが読み込まれたとき) 既定でチェックボックスがチェックされていることを示します。このチェックボックスが現在チェックされているかどうかを示すものではありません。チェックボックスの状態が変更された場合でも、このコンテンツ属性はその変更を反映しません。 (HTMLInputElementchecked IDL 属性のみが更新されます。)

注: 他の入力コントロールとは異なり、チェックボックスやラジオボタンの値は、現在 checked の状態にある場合に送信データに含まれます。存在する場合、チェックされたコントロールの名前と値が送信されます。

例えば、 namefruit で、 valuecherry であるチェックボックスがチェックされていると、送信されるフォームデータには fruit=cherry が含まれます。チェックボックスがチェックされていない場合、フォームデータには全く含まれません。チェックボックスやラジオボタンの既定の valueon です。

{{htmlattrdef("dirname")}}

text および search 入力型のみに有効で、 dirname 属性によって要素の書字方向を送信することができます。これが含まれていると、フォームコントロールは2組の名前と値を送信します。1組目は namevalue であり、2組目は名前が dirname の値で、値に ltr または rtl がブラウザーによって設定されます。

<form action="page.html" method="post">
  <label>Fruit: <input type="text" name="fruit" dirname="fruit.dir" value="cherry"></label>
  <input type="submit"/>
</form>
<!-- page.html?fruit=cherry&fruit.dir=ltr -->

上記のフォームが送信されると、入力欄は name / value の組である fruit=cherry と、 dirname / 書字方向の組である fruit.dir=ltr が送信されます。

{{htmlattrdef("disabled")}}

論理属性で、存在する場合、ユーザーが入力欄と対話できないことを示します。無効な入力欄は、ふつうより薄い色や、その他のフィールドが使用できないことを示すことを示す形で表示されます。

特に、無効になった入力欄は {{domxref("Element/click_event", "click")}} イベントを受け取らず、フォームと共に送信されることもありません。

メモ: 仕様書で要件とはされていませんが、 Firefox は既定で、ページを再読み込みしても <input>動的に無効化した状態を維持します。この機能は {{htmlattrxref("autocomplete","input")}} 属性で制御することができます。

{{htmlattrdef("form")}}

文字列で、入力欄が関連づけられた {{HTMLElement("form")}} 要素 (つまり、フォームオーナー) を指定します。存在する場合、この文字列値は同一文書内の <form> 要素の {{htmlattrxref("id")}} と一致している必要があります。この属性が指定されない場合は、 <input> 要素は直近の内包するフォームに (もしあれば) 関連付けられます。

form 属性によって、入力欄を文書内のどこに置いても、文書内の他の場所にあるフォームと関連付けることができます。

メモ: 入力欄は一つのフォームとしか関連付けることができません。

{{htmlattrdef('formaction')}}

image および submit 入力型でのみ有効です。詳しくは {{HTMLElement("input/submit", "submit")}} 入力型を参照してください。

{{htmlattrdef('formenctype')}}

image および submit 入力型でのみ有効です。詳しくは {{HTMLElement("input/submit", "submit")}} 入力型を参照してください。

{{htmlattrdef('formmethod')}}

image および submit 入力型でのみ有効です。詳しくは {{HTMLElement("input/submit", "submit")}} 入力型を参照してください。

{{htmlattrdef('formnovalidate')}}

image および submit 入力型でのみ有効です。詳しくは {{HTMLElement("input/submit", "submit")}} 入力型を参照してください。

{{htmlattrdef('formtarget')}}

image および submit 入力型でのみ有効です。詳しくは {{HTMLElement("input/submit", "submit")}} 入力型を参照してください。

{{htmlattrdef("height")}}

image 入力型でのみ有効です。 height はグラフィックの送信ボタンの表現を表示するための画像ファイルの高さを示します。 {{HTMLElement("input/image", "image")}} 入力型を参照してください。

{{htmlattrdef("id")}}

すべての入力欄を含む、すべての要素で有効なグローバル属性で、文書全体で一意でなければならない一意の識別子 (ID) を定義します。その目的は、リンクする際に要素を識別することです。この値は、ラベルとフォームコントロールをリンクするための {{htmlelement('label')}} の for 属性の値として使用されます。 {{htmlelement('label')}} を参照してください。

{{htmlattrdef("inputmode")}}

すべての要素で有効なグローバル属性です、この要素やその内容を編集する際に使用される仮想キーボード設定の種類をブラウザーに示すヒントを提供します。値としては none, text, tel, url, email, numeric, decimal, search があります。

{{htmlattrdef("list")}}

list 属性で与えられる値は、同じ文書内にある {{HTMLElement("datalist")}} 要素の {{domxref("Element.id", "id")}} としてください。 <datalist> は、この入力欄でユーザーに提案する事前定義された値のリストを提供します。リストに {{htmlattrxref("type", "input")}} と互換性のない値が含まれていた場合は、提案の選択肢には含まれません。この値は提案として使用されるものであり、要件ではありません。ユーザーはこの定義済みリストから選択することもできるし、別な値を提供することもできます。

{{EmbedLiveSample("datalist",400,275,"","", "nobutton")}}

これは text, search, url, tel, email, date, month, week, time, datetime-local, number, range, color で有効です。

仕様書によれば、 list 属性は hidden, password, checkbox, radio, file それにボタン型では対応していません。

ブラウザーによっては、カスタムカラーパレットが提案されたり、範囲に沿ったチェックマークが表示されたり、{{HTMLElement("select")}}のように開くものの、リストにない値を入力できるようになったりすることもあります。他の入力型についてはブラウザーの互換性一覧表を参照してください。

{{htmlelement('datalist')}} 要素を参照してください。

{{htmlattrdef("max")}}

date, month, week, time, datetime-local, number, range で有効であり、許可される値の範囲の最大値を定義します。要素に入力された {{htmlattrxref("value", "input")}} がこれを超えた場合、要素は制約の検証に失敗します。 max 属性の値が数値でない場合は、要素に最大値は設定されません。

特殊な場合があります。データ型が期間を表す場合 (日付や時刻など)、 max の値は min の値よりも小さくなる場合があり、これは範囲が折り返す可能性があることを表します。例えば、これによって午後10時から午前4時までの自国の範囲を指定することができます。

{{htmlattrdef("maxlength")}}

text, search, url, tel, email, password で有効であり、ユーザーがフィールドに入力することができる文字数 (UTF-16 コード単位) を定義します。これは 0 以上の整数値でなければなりません。 maxlength が指定されなかった場合、または無効な値が指定された場合は、その入力欄には最大長が設定されません。この値は minlength の値以上である必要もあります。

欄に入力されたテキストの文字数が UTF-16 コード単位で maxlength よりも多いと、この入力欄は制約の検証に失敗します。既定では、ブラウザーはユーザーが maxlength 属性で許可された文字数以上を入力するのを防ぎます。詳しくは{{anch("Client-side validation", "クライアント側検証")}}を参照してください。

{{htmlattrdef("min")}}

date, month, week, time, datetime-local, number, range で有効であり、許可される値の範囲の最も低い値を定義します。要素に入力された {{htmlattrxref("value", "input")}} がこれを下回った場合、要素は制約の検証に失敗します。 min 属性の値が数値でない場合は、要素に最小値は設定されません。

この値は max 属性の値以下である必要があります。 min 属性が存在するものの、指定されていなかったり無効であったりした場合は、 min の値は適用されません。 min 属性が有効であり、値が空ではなく min 属性で許可された最小値よりも小さかった場合、制約の検証によりフォームの送信が行われません。詳しくは{{anch("Client-side validation", "クライアント側検証")}}を参照してください。

特殊な場合があります。データ型が期間を表す場合 (日付や時刻など)、 max の値は min の値よりも小さくなる場合があり、これは範囲が折り返す可能性があることを表します。例えば、これによって午後10時から午前4時までの自国の範囲を指定することができます。

{{htmlattrdef("minlength")}}

text, search, url, tel, email, password で有効であり、ユーザーがフィールドに入力することができる最小文字数 (UTF-16 コード単位) を定義します。これは負数ではなく、 maxlength で指定された値以下の整数値でなければなりません。 minlength が指定されなかった場合、または無効な値が指定された場合は、その入力欄には最小文字数が設定されません。

欄に入力されたテキストの文字数が UTF-16 コード単位で minlength よりも少ないと、この入力欄は制約の検証に失敗します。詳しくは{{anch("Client-side validation", "クライアント側検証")}}を参照してください。

{{htmlattrdef("multiple")}}

論理属性の multiple は、設定されている場合、ユーザーがウィジェット内でコンマ区切りで複数のメールアドレスを入力できること、または file 入力欄で複数のpファイルを選択することが出えきるinput. See the {{HTMLElement("input/email", "email")}} and {{HTMLElement("input/file", "file")}} input type.

{{htmlattrdef("name")}}

入力コントロールの名前を指定する文字列です。この名前はフォームデータが送信される時に、コントロールの値と共に送信されます。

name に入れるもの

name は (厳密にはそうではありませんが) 必須の属性と考えてください。入力欄に name が指定されていなかった場合や name が空欄だった場合、その入力欄の値はフォームと一緒に送信されません。 (無効なコントロール、チェックされていないラジオボタン、チェックされていないチェックボックス、リセットボタンも送信されません。)

特殊な場合が2つあります。

  1. _charset_ : <input> 要素の {{HTMLElement("input/hidden", "hidden")}} 型として使用された場合、入力欄の value には自動的に、フォームを送信するのに使用される文字エンコーディングが{{Glossary("user agent", "ユーザーエージェント")}}によって設定されます。
  2. isindex: 歴史的な理由で、 isindex という名前は許可されていません。
name とラジオボタン

name 属性はラジオボタンでは独特の動きをします。

同名のラジオボタングループ内で、一度にチェックできるラジオボタンは1つのみです。そのグループ内のラジオボタンを選択すると、同じグループ内の現在選択されているラジオボタンの選択が自動的に解除されます。チェックされたラジオボタンの値は、フォームが送信された場合、名前と一緒に送信されます。

同名のラジオボタンが連続したグループにタブ移動した場合、そのうちの1つにチェックが入っていると、それがフォーカスを受け取ります。ソース順でグループ化されていない場合、グループのうちの1つがチェックされていた場合は、タブ移動でグループ内の最初のラジオボタンに出会ったときに、チェックが入っていないラジオボタンをすべてスキップして、そのグループがフォーカスを受け取ります。言い換えれば、1つがチェックされている場合、グループ内のチェックされていないラジオボタンはスキップされます。どれもチェックされていない場合、同名グループの最初のボタンに到達したときに、ラジオボタングループがフォーカスを受け取ります。

グループ内のラジオボタンにフォーカスがある場合、矢印キーを使用すれば、ラジオボタンがソースの順序でグループ化されていなくても、同じ名前のすべてのラジオボタンに移動することができます。

HTMLFormElement.elements

入力要素に name が与えられると、その名前は所有するフォーム要素の {{domxref("HTMLFormElement.elements")}} プロパティのプロパティになります。 nameguest に設定されている入力と、 namehat-size に設定されている入力がある場合、以下のコードを使用することができます。

let form = document.querySelector("form");

let guestName = form.elements.guest;
let hatSize = form.elements["hat-size"];

このコードを実行すると、 guestName が {{domxref("HTMLInputElement")}} の guest フィールドになり、 hatSizehat-size フィールドの

警告: フォームの組み込みプロパティに対応する name をフォーム要素に与えないようにします。なぜなら、対応する入力への参照で定義済みのプロパティやメソッドをオーバーライドしてしまうからです。

{{htmlattrdef("pattern")}}

pattern 属性は、指定された場合、入力の {{htmlattrxref("value")}} が一致すれば値が制約の検証を通過したとみなされる正規表現を指定します。これは {{jsxref("RegExp")}} 型で使用される有効な JavaScript の正規表現でなければならず、これは正規表現のガイドで説明されている通りです。正規表現をコンパイルする際には 'u' フラグが指定され、パターンが ASCII ではなく Unicode コードポイントのシーケンスとして扱われます。パターンのテキストの周囲にスラッシュを指定しないでください。

pattern 属性が存在するが、指定されていないか無効な場合、正規表現は適用されず、この属性は完全に無視されます。 pattern 属性が有効で、空でない値がパターンと一致しない場合、制約の検証によりフォームの送信ができなくなります。

ヒント: pattern 属性を使用する場合は、期待される書式をユーザーに知らせる説明文を近くに配置してください。また、パターンに一致させるための要件が何であるかを説明するために、 {{htmlattrxref("title", "input")}} 属性を含めることもできます。ほとんどのブラウザーはこのタイトルをツールチップとして表示します。ツールチップは改善手段です。

詳しくは{{anch("Client-side validation", "クライアント側検証")}}を参照してください。

{{htmlattrdef("placeholder")}}

placeholder 属性は、フィールドでどのような情報が期待されているかについて、ユーザーに簡単なヒントを与える文字列です。説明的なメッセージではなく、予想されるデータのタイプを示す単語または短いフレーズである必要があります。テキストには、改行を含めてはいけません

注: placeholder 属性は、フォームを説明するためには他の方法ほど意味的に有用ではなく、コンテンツに予期せぬ技術的な問題を引き起こす可能性があります。詳細は{{SectionOnPage("/ja/docs/Web/HTML/Element/input", "Labels")}}を参照してください。

{{htmlattrdef("readonly")}}

論理属性で、存在すれば、ユーザーが入力欄の値を編集できないことを示します。 readonly 属性は text, search, url, tel, email, date, month, week, time, datetime-local, number, password の各入力型が対応しています。

詳しくは HTML attribute: readonly を参照してください。

{{htmlattrdef("required")}}

required は論理属性であり、所有するフォームが送信される前に、ユーザーが入力欄の値を指定しなければならないことを示します。 required 属性は text, search, url, tel, email, date, month, week, time, datetime-local, number, password, checkbox, radio, file の各入力型で対応しています。

See {{anch("Client-side validation")}} and the HTML attribute: required for more information.

{{htmlattrdef("size")}}
Valid for email, password, tel, and text input types only. Specifies how much of the input is shown. Basically creates same result as setting CSS width property with a few specialities. The actual unit of the value depends on the input type. For password and text it's number of characters (or em units) and pixels for others. CSS width takes precedence over size attribute.
{{htmlattrdef("src")}}

Valid for the image input button only, the src is string specifying the URL of the image file to display to represent the graphical submit button. See the {{HTMLElement("input/image", "image")}} input type.

{{htmlattrdef("step")}}

Valid for the numeric input types, including number, date/time input types, and range, the step attribute is a number that specifies the granularity that the value must adhere to.

If not explicitly included, step defaults to 1 for number and range, and 1 unit type (second, week, month, day) for the date/time input types. The value can must be a positive number—integer or float—or the special value any, which means no stepping is implied, and any value is allowed (barring other constraints, such as {{anch("min")}} and {{anch("max")}}).

If any is not explicity set, valid values for the number, date/time input types, and range input types are equal to the basis for stepping - the {{anch("min")}} value and increments of the step value, up to the {{anch("max")}} value, if specified.

For example, if you have <input type="number" min="10" step="2">, then any even integer, 10 or greater, is valid. If omitted, <input type="number">, any integer is valid, but floats (like 4.2) are not valid, because step defaults to 1. For 4.2 to be valid, step would have had to be set to any, 0.1, 0.2, or any the min value would have had to be a number ending in .2, such as <input type="number" min="-5.2">

Note: When the data entered by the user doesn't adhere to the stepping configuration, the value is considered invalid in contraint validation and will match the :invalid pseudoclass.

The default stepping value for number inputs is 1, allowing only integers to be entered, unless the stepping base is not an integer. The default stepping value for time is 1 second (with 900 being equal to 15 minutes).

See {{anch("Client-side validation")}} for more information.

{{htmlattrdef("tabindex")}}

Global attribute valid for all elements, including all the input types, an integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. As all input types except for input of type hidden are focusable, this attribute should not be used on form controls, because doing so would require the management of the focus order for all elements within the document with the risk of harming usability and accessibility if done incorrectly.

{{htmlattrdef('title')}}

Global attribute valid for all elements, including all input types, containing a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip. The title should NOT be used as the primary explanation of the purpose of the form control. Instead, use the {{htmlelement('label')}} element with a for attribute set to the form control's {{htmlattrdef('id')}} attribute. See {{anch("Labels")}} below.

{{htmlattrdef("type")}}

文字列で、表示するコントロールの型を指定します。例えば、チェックボックスを生成するには、 checkbox の値が使用されます。省略された場合 (または不明な値が指定された場合) は、入力型に text が使用され、テキストの入力欄が生成されます。

許可されている値は{{anch("<input> types", "<input> の型")}}にあります。

{{htmlattrdef("value")}}

入力コントロールの値です。 HTML の中で指定されると、これは初期値となり、その後で JavaScript を使用してそれぞれの {{domxref("HTMLInputElement")}} オブジェクトの value プロパティにアクセスすることで、いつでも変更したり受け取ったりすることができます。 value 属性は常に省略可ですが、 checkbox, radio, hidden においては必須だと考えてください。

{{htmlattrdef("width")}}

Valid for the image input button only, the width is the width of the image file to display to represent the graphical submit button. See the {{HTMLElement("input/image", "image")}} input type.

標準外の属性

The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped.

属性 説明
{{anch("autocorrect")}} A string indicating whether or not autocorrect is on or off. Safari only.
{{anch("incremental")}} Whether or not to send repeated {{domxref("HTMLInputElement/search_event", "search")}} events to allow updating live search results while the user is still editing the value of the field. WebKit and Blink only (Safari, Chrome, Opera, etc.).
{{anch("mozactionhint")}} A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only.
{{anch("orient")}} Sets the orientation of the range slider. Firefox only.
{{anch("results")}} The maximum number of items that should be displayed in the drop-down list of previous search queries. Safari only.
{{anch("webkitdirectory")}} A Boolean indicating whether or not to only allow the user to choose a directory (or directories, if {{anch("multiple")}} is also present)
{{htmlattrdef("autocorrect")}} {{non-standard_inline}}
{{page("/ja/docs/Web/HTML/Element/input/text", "autocorrect-include")}}
{{htmlattrdef("incremental")}} {{non-standard_inline}}
{{page("/ja/docs/Web/HTML/Element/input/search", "incremental-include")}}
{{htmlattrdef("mozactionhint")}} {{non-standard_inline}}
{{page("/en-US/docs/Web/HTML/Element/input/text", "mozactionhint-include")}}
{{htmlattrdef("orient")}} {{non-standard_inline}}
{{page("/en-US/docs/Web/HTML/Element/input/range", "orient-include")}}
{{htmlattrdef("results")}} {{non-standard_inline}}
{{page("/en-US/docs/Web/HTML/Element/input/search", "results-include")}}
{{htmlattrdef("webkitdirectory")}} {{non-standard_inline}}
{{page("/en-US/docs/Web/HTML/Element/input/file", "webkitdirectory-include")}}

メソッド

以下のメソッドは DOM 内で <input> を表現する {{domxref("HTMLInputElement")}} インターフェイスで提供されます。親インターフェイスである {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, {{domxref("EventTarget")}} で指定されているメソッドも使用できます。

{{domxref("HTMLInputElement.checkValidity", "checkValidity()")}}
要素の妥当性チェックを直ちに実行し、値が妥当でない場合は文書に対して {{domxref("HTMLInputElement.invalid_event", "invalid")}} イベントを要素に発生させます。
{{domxref("HTMLInputElement.reportValidity", "reportValidity()")}}
要素の値が妥当性チェックを通った場合は true を返します。そうでなければ、 false を返します。
{{domxref("HTMLInputElement.select", "select()")}}
要素が選択可能な場合、 <input> 要素の内容を選択します。選択可能なテキストコンテンツがない要素 (カラーピッカーまたはカレンダー日付入力など) では、このメソッドは何もしません。
{{domxref("HTMLInputElement.setCustomValidity", "setCustomValidity()")}}
入力要素の値が妥当ではないときに表示するカスタムメッセージを設定します。
{{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}
入力要素内の文字の指定された範囲のコンテンツを、指定された文字列に設定します。 selectMode 引数を使用して、既存のコンテンツに影響させる方法を制御することができます。
{{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}
テキストの入力要素内で、指定された文字の範囲を選択します。テキスト入力欄として表現されない入力欄では何もしません。
{{domxref("HTMLInputElement.stepDown", "stepDown()")}}
数値入力欄の値を既定で1、または指定された数値の単位だけ減少させます。
{{domxref("HTMLInputElement.stepUp", "stepUp()")}}
数値入力欄の値を既定で1、または指定された数値の単位だけ増加させます。

CSS

Inputs, being replaced elements, have a few features not applicable to non form elements. There are CSS selectors that can specification target form controls based on their UI features, also known as UI pseudo-classes. The input element can also be targeted by type with attribute selectors. There are some properties that are especially useful as well.

UI 擬似クラス

Captions super relevant to the {{htmlelement("input")}} element:
擬似クラス 説明
{{Cssxref(":enabled")}} Any currently enabled element that can be activated (selected, clicked on, typed into, etc.) or accept focus and also has a disabled state, in which it can't be activated or accept focus.
{{Cssxref(":disabled")}} Any currently disabled element that has an enabled state, meaing it otherwise could be activated (selected, clicked on, typed into, etc.) or accept focus were it not disabled.
{{Cssxref(":read-only")}} Element not editable by the user
{{Cssxref(":read-write")}} Element that is editable by the user.
{{Cssxref(":placeholder-shown")}} Element that is currently displaying placeholder text, including {{HTMLElement("input")}} and {{HTMLElement("textarea")}} elements with the {{anch('htmlattrdefplaceholder', 'placeholder')}} attribute present that has, as of yet, no value.
{{Cssxref(":default")}} Form elements that are the default in a group of related elements. Matches {{HTMLElement("input/checkbox", "checkbox")}} and {{HTMLElement("input/radio", "radio")}} input types that were checked on page load or render.
{{Cssxref(":checked")}} Matches {{HTMLElement("input/checkbox", "checkbox")}} and {{HTMLElement("input/radio", "radio")}} input types that are currently checked (and the ({{HTMLElement("option")}} in a {{HTMLElement("select")}} that is currently selected).
{{Cssxref(":indeterminate")}} {{HTMLElement("input/checkbox", "checkbox")}} elements whose indeterminate property is set to true by JavaScript, {{HTMLElement("input/radio", "radio")}} elements, when all radio buttons with the same name value in the form are unchecked, and {{HTMLElement("progress")}} elements in an indeterminate state
{{Cssxref(":valid")}} Form controls that can have constraint validation applied and are currently valid.
{{Cssxref(":invalid")}} Form controls that have constraint validation applied and are currently not valid. Matches a form control whose value doesn't match the constraints set on it by it's attributes, such as {{anch('htmlattrdefrequired', 'required')}}, {{anch('htmlattrdefpattern', 'pattern')}} , {{anch('htmlattrdefstep', 'step')}} and {{anch('htmlattrdefmax', 'max')}}.
{{Cssxref(":in-range")}} A non-empty input whose current value is within the range limits specified by the {{anch('htmlattrdefmin', 'min')}} and {{anch('htmlattrdefmax', 'max')}} attributes and the {{anch('htmlattrdefstep', 'step')}} .
{{Cssxref(":out-of-range")}} A non-empty input whose current value is NOT within the range limits specified by the {{anch('htmlattrdefmin', 'min')}} and {{anch('htmlattrdefmax', 'max')}} attributes or does not adher to the {{anch('htmlattrdefstep', 'step')}} constraint.
{{Cssxref(":required")}} {{HTMLElement("input")}}, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element that has the {{ htmlattrxref("required", "input")}} attribute set on it. Only matches elements that can be required. The attribute included on a non-requirable element will not make for a match.
{{Cssxref(":optional")}} {{HTMLElement("input")}}, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element that does NOT have the {{ htmlattrxref("required", "input")}} attribute set on it. Does not match elements that can't be required.
{{Cssxref(":blank")}} {{HTMLElement("input")}} and {{HTMLElement("textarea")}} elements that currently have no value.
{{Cssxref(":user-invalid")}} Similar to :invalid, but is activated on blur. Matches invalid input but only after the user interaction, such as by focusing on the control, leaving the control, or attempting to submit the form containing the invalid control.

We can style a checkbox label based on whether the checkbox is checked or not. In this example, we are styling the {{cssxref('color')}} and {{cssxref('font-weight')}} of the {{htmlelement('label')}} that comes immediately after a checked input. We haven't applied any styles if the input is not checked.

input:checked + label {
  color: red;
  font-weight: bold;
}

{{EmbedLiveSample('checkbox_label', 500, 80)}}

属性セレクター

It is possible to target different types of form controls based on their {{anch('htmlattrdeftype', 'type')}} using attribute selectors. CSS attribute selectors match elements based on either just the presence of a attribute or the value of a given attribute.

/* matches a password input */
input[type="password"] {}

/* matches a form control whose valid values are limited to a range of values*/
input[min][max] {}

/* matches a form control with with a pattern attribute */
 input[pattern] {}

::placeholder

By default, the appearance of placeholder text is a translucent or light gray. The {{cssxref('::placeholder')}} pseudo-element is the input's placeholder text. It can be styled with a limited subset of CSS properties.

::placeholder {
  color: blue;
}

Only the subset of CSS properties that apply to the {{cssxref("::first-line")}} pseudo-element can be used in a rule using ::placeholder in its selector.

appearance

The {{cssxref("appearance")}} property enables the displaying of (almost) any element as a platform-native style based on the operating system's theme as well as the removal of any platform-native styling with the none value.

You could make a <div> look like a radio button with div {appearance: radio;} or a radio look like a checkbox with [type="checkbox] {appearance: checkbox;}, but don't.

Setting appearance: none removes platform native borders, but not functionality.

caret-color

A property specific to text entry-related elements is the CSS {{cssxref("caret-color")}} property, which lets you set the color used to draw the text input caret:

HTML

<label for="textInput">Note the red caret:</label>
<input id="textInput" class="custom" size="32">

CSS

input.custom {
  caret-color: red;
  font: 16px "Helvetica", "Arial", "sans-serif"
}

結果

{{EmbedLiveSample('caret-color', 500, 80)}}

object-position と object-fit

In certain cases (typically involving non-textual inputs and specialized interfaces), the <input> element is a replaced element. When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS {{cssxref("object-position")}} and {{cssxref("object-fit")}} properties

スタイル付け

For more information about adding color to elements in HTML, see:

Also see:

追加機能

ラベル

ラベルは支援テキストを <input> に関連付けるために必要です。 {{HTMLElement("label")}} 要素は、フォームの入力欄を説明するために、 (レイアウト方法はさておき) 常に適切な手段です。 <label><input> や {{HTMLElement("textarea")}} に何を入力するべきかを説明するのに使用することは、決して悪い考えではありません。

関連付けられたラベル

The semantic pairing of <input> and <label> elements is useful for assistive technologies such as screen readers. By pairing them using the <label>'s {{htmlattrxref("for", "label")}} attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely.

It does not suffice to have plain text adjacent to the <input> element,. Rather, usability and accessibility requires the inclusion of either implicit or explicit {{HTMLElement("label")}}:

<!-- inaccessible -->
<p>Enter your name: <input id="name" type="text" size="30"></p>

<!-- implicit label -->
<p><label>Enter your name: <input id="name" type="text" size="30"></label></p>

<!-- explicit label -->
<p><label for="name">Enter your name: </label><input id="name" type="text" size="30"></p>

The first example is inaccessible: no relationship exists between the prompt and the <input> element.

In addition to an accessible name, the label provides a larger 'hit' area for mouse and touch screen users to click on or touch. By pairing a <label> with an <input>, clicking on either one will focus the <input>. If you use plain text to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions.

As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your web site—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels.

プレイスホルダーはアクセシブルではない

{{htmlattrxref("placeholder", "input")}} 属性で、 <input> 要素が空の時にコンテンツ領域に表示されるテキストを指定することができます。プレイスホルダーは、フォームを理解するために必要なものであってはいけません。ラベルではありませんし、その代用として使用すべきではありません。プレイスホルダーは入力例を示すために使用されるものであり、説明やプロンプトではありません。プレイスホルダーは、読み上げソフトがアクセスできないだけでなく、ユーザーがフォームコントロールにテキストを入力したり、フォームコントロールにすでに値があったりする場合、プレイスホルダーはなくなります。自動ページ翻訳機能を持つブラウザーは、翻訳時にこの属性をスキップする、すなわち placeholder が翻訳されないことがあります。

避けることができるのであれば、 {{htmlattrxref("placeholder", "input")}} 属性を使用しないでください。 <input> 要素にラベルを付ける樋津陽があるのであれば、 {{HTMLElement("label")}} 属性を使用してください。

クライアント側検証

In addition to using CSS to style inputs based on the {{cssxref(":valid")}} or {{cssxref(":invalid")}} UI states based on the current state of each input, as noted in the {{anch('UI pseudo-classes')}} section above, the browser provides for client-side validation on (attempted) form submission. On form submission, if there is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you.

Some input types and other attributes place limits on what values are valid for a given input. For example, <input type="number" min="2" max="10" step="2"> means only the number 2, 4, 6, 8, or 10 are valid. Several errors could occur, including a rangeUnderflow error if the value is less than 2, rangeOverflow if greater than 10, stepMismatch if the value is a number between 2 and 10, but not an even integer (does not match the requirements of the step attribute), or typeMismatch if the value is not a number.

For the input types whose domain of possible values is periodic (that is, at the highest possible value, the values wrap back around to the beginning rather than ending), it's possible for the values of the {{htmlattrxref("max")}} and {{htmlattrxref("min")}} properties to be reversed, which indicates that the range of permitted values starts at min, wraps around to the lowest possible value, then continues on until max is reached. This is particularly useful for dates and times, such as when you want to allow the range to be from 8 PM to 8 AM:

<input type="time" min="20:00" max="08:00" name="overnight">

Specific attributes and their values can lead to a specific error {{domxref('ValidityState')}}:

Validity object errors depend on the {{htmlelement('input')}} attributes and their values:
属性 関連するプロパティ/th> 説明
{{anch('htmlattrdefmax', 'max')}} {{domxref('validityState.rangeOverflow')}} Occurs when the value is greater than the maximum value as defined by the max attribute
{{anch('htmlattrdefmaxlength', 'maxlength')}} {{domxref('validityState.tooLong')}} Occurs when the number of characters is greater than the number allowed by the maxlength property
{{anch('htmlattrdefmin', 'min')}} {{domxref('validityState.rangeUnderflow')}} Occurs when the value is less than the minimum value as defined by the min attribute
{{anch('htmlattrdefminlength', 'minlength')}} {{domxref('validityState.tooShort')}} Occurs when the number of characters is less than the number required by the minlength property
{{anch('htmlattrdefpattern', 'pattern')}} {{domxref('validityState.patternMismatch')}} Occurs when a pattern attribute is included with a valid regular expression and the value does not match it.
{{anch('htmlattrdefrequired', 'required')}} {{domxref('validityState.valueMissing')}} Occurs when the required attribute is present but the value is null or radio or checkbox is not checked.
{{anch('htmlattrdefstep', 'step')}} {{domxref('validityState.stepMismatch')}} The value doesn't match the step increment. Increment default is 1, so only integers are valid on type="number" is step is not included. step="any" will never throw this error.
{{anch('htmlattrdeftyoe', 'type')}} {{domxref('validityState.typeMismatch')}} Occurs when the value is not of the correct type, for example a email does not contain an @ or a url doesn't contain a protocol.

フォームコントロールに required 属性がない場合、値がない場合や空文字列出会った場合は無効にはなりません。 required 以外の上記の属性があった場合も、空文字列でエラーにはなりません。

We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted.

In addition to the errors described in the table above, the validityState interface contains the badInput, valid, and customError boolean readonly properties. The validity object includes:

For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints.

If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or null), the form will be be prevented from being submitted. If there is no custom error message, and none of the other properties return true, valid will be true, and the form can be submitted.

function validate(input) {
  let validityState_object = input.validity;
  if(validityState_object.valueMissing) {
     input.setCustomValidity('A value is required');
  } else if (input.rangeUnderflow) {
    input.setCustomValidity('Your value is too low');
  } else if (input.rangeOverflow) {
    input.setCustomValidity('Your value is too high');
  } else {
    input.setCustomValidity('');
  }
}

The last line, setting the custom validity message to the error string is vital. If the user makes an error, and the validity is set, it will fail to submit, even if all of the values are valid, until the message is null.

フィールドの検査に失敗したときに、独自のエラーメッセージを表示させたい場合は、 <input> (および関連する) 要素で利用できる制約検証機能を使用する必要があります。以下のような形を取ってください。

<form>
  <label for="name">ユーザー名を入力してください (英大文字および小文字): </label>
  <input type="text" name="name" id="name" required pattern="[A-Za-z]+">
  <button>Submit</button>
</form>

基本的な HTML フォーム検証機能では、フォームを送信しようとしたときに、有効な値が入力されていなかったり、 pattern と一致しない値が入力されていたりすると、既定のエラーメッセージを生成します。

独自のエラーメッセージで代替したい場合は、以下のような JavaScript を使用することができます。

const nameInput = document.querySelector('input');
const form = document.querySelector('form');

nameInput.addEventListener('input', () => {
  nameInput.setCustomValidity('');
  nameInput.checkValidity();
});

nameInput.addEventListener('invalid', () => {
  if(nameInput.value === '') {
    nameInput.setCustomValidity('名前を入力してください。');
  } else {
    nameInput.setCustomValidity('ユーザー名には英大文字と小文字のみが使えます。入力しなおしてください。');
  }
});

この例は次のように表示されます。

{{EmbedLiveSample('Client-side_validation')}}

簡単に言えば、以下の通りです。

Note: Always validate input constraints both client side and server side. Constraint validation doesn't remove the need for validation on the server side. Invalid values can still be sent by older browsers or by bad actors.

メモ: Firefox は多くの版で、同様の方法で独自のエラーメッセージを設定することができる、独自のエラー属性 — x-moz-errormessage — に対応していました。これはバージョン66で削除されました ({{bug(1513890)}} を参照)。

ローカライゼーション

<input> 型によっては、入力可能な文字列がロケールに依存します。ロケールによっては 1,000.00 が有効な数値である一方、ロケールによっては有効な数値は 1.000,00 です。

Firefox は (少なくとも type="number" において) ユーザーの入力内容を検証する際に、ロケールを特定するために以下の経験則を使用します。

技術的概要

コンテンツカテゴリ フローコンテンツ、リスト化、サブミット可能、リセット可能、フォーム関連要素、記述コンテンツ。{{htmlattrxref("type", "input")}} の値が hidden でない場合はラベル付け可能要素、知覚可能コンテンツ。
許可されている内容 なし。これは{{Glossary("empty element", "空要素")}}です。
タグの省略 開始タグは必須。終了タグを記述してはなりません。
許可されている親要素 記述コンテンツを受け入れるすべての要素。
Implicit ARIA role
  • type=button: button
  • type=checkbox: checkbox
  • type=email
    • with no list attribute: textbox
    • with list attribute: {{ARIARole("combobox")}}
  • type=image: button
  • type=number: {{ARIARole("spinbutton")}}
  • type=radio: {{ARIARole("radio")}}
  • type=range: {{ARIARole("slider")}}
  • type=reset: button
  • type=search
    • with no list attribute: {{ARIARole("searchbox")}}
    • with list attribute: {{ARIARole("combobox")}}
  • type=submit: button
  • type=tel
    • with no list attribute: textbox
    • with list attribute: {{ARIARole("combobox")}}
  • type=text
    • with no list attribute: textbox
    • with list attribute: {{ARIARole("combobox")}}
  • type=url
    • with no list attribute: textbox
    • with list attribute: {{ARIARole("combobox")}}
  • type=color|date|datetime-local|file|hidden|month|password|time|week: no corresponding role
許可されている ARIA ロール
  • type=button: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("option")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}, {{ARIARole("tab")}}
  • type=checkbox: {{ARIARole("button")}} when used with aria-pressed, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("option")}}, {{ARIARole("switch")}}
  • type=image: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}
  • type=radio: {{ARIARole("menuitemradio")}}
  • type=text with no list attribute: {{ARIARole("combobox")}}, {{ARIARole("searchbox")}}, {{ARIARole("spinbutton")}}
  • type=color|date|datetime|datetime-local|email|file|hidden|month|number|password|range|reset|search|submit|tel|url|week または textlist 属性が付いたもの: 許可されている role なし
DOM インターフェイス {{domxref("HTMLInputElement")}}

仕様書

仕様書 状態 備考
{{SpecName('HTML WHATWG', 'forms.html#the-input-element', '<input>')}} {{Spec2('HTML WHATWG')}}
{{SpecName('HTML Media Capture', '#the-capture-attribute','capture attribute')}} {{Spec2('HTML Media Capture')}} capture 属性を追加
{{SpecName('HTML5 W3C', 'sec-forms.html#the-input-element', '<input>')}} {{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'interact/forms.html#h-17.4', '<form>')}} {{Spec2('HTML4.01')}}

アクセシビリティの考慮事項

ラベル

When including inputs, it is an accessibilty requirement to add labels along side. This is needed so those who use assistive technologies can tell what the input is for. Also, clicking or touching a label gives focus to the label's associated form control. This improves the accessibility and usability for sighted users, increases the area a user can click or touch to activate the form control. this is especially useful (and even needed) for radio buttons and checkboxes, which are tiny. For more information about labels in general see {{anch("Labels")}} .

次の例は、上記の形で <label><input> 要素に関連付ける方法の例です。 <input>id 属性を設定する必要があります。そして <label> には入力欄の id と同じ値を持つ for 属性が必要になります。

<label for="peas">Do you like peas?</label>
<input type="checkbox" name="peas" id="peas">

大きさ

フォーム入力欄のような対話型要素は、簡単に有効化できるだけの大きさを持たせてください。これにより、手足の不自由な人や、スタイラスや指のような精度の低い入力方法を使用している人など、様々な人にとって有用です。対話型の大きさとしては、 44×44 CSS ピクセル を最小値とすることが推奨されています。

ブラウザーの互換性

{{Compat("html.elements.input")}}

関連情報