このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

:required

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

:requiredCSS擬似クラスで、 <input>, <select>, <textarea> 要素のうち required 属性が設定されているものを表します。

css
/* 必須の <input> をすべて選択 */ input:required { border: 1px dashed red; } 

試してみましょう

label { display: block; margin-top: 1em; } .req { color: red; } *:required { background-color: gold; } 
<form> <label for="name">Name: <span class="req">*</span></label> <input id="name" name="name" type="text" required /> <label for="birth">Date of Birth:</label> <input id="birth" name="birth" type="date" /> <label for="origin" >How did you find out about us? <span class="req">*</span></label > <select id="origin" name="origin" required> <option>Google</option> <option>Facebook</option> <option>Advertisement</option> </select> <p><span class="req">*</span> - Required field</p> </form> 

この擬似クラスは、フォームを送信する前に有効なデータを持っている必要がある入力欄を強調表示するのに便利です。

メモ: :optional 擬似クラスは省略可能なフォーム欄を選択します。

構文

:required 

必須フィールドの枠を赤にする

HTML

html
<form> <div class="field"> <label for="url_input">Enter a URL:</label> <input type="url" id="url_input" /> </div> <div class="field"> <label for="email_input">Enter an email address:</label> <input type="email" id="email_input" required /> </div> </form> 

CSS

css
label { display: block; margin: 1px; padding: 1px; } .field { margin: 1px; padding: 1px; } input:required { border-color: #800000; border-width: 3px; } input:required:invalid { border-color: #c00000; } 

結果

アクセシビリティの考慮

入力が必須の <input> には required 属性を適用してください。これによって、読み上げソフトなどの支援技術を使用している人が、フォームを送信するためにどの入力欄が有効なコンテンツを必要とするかを理解することができます。

フォームに任意の入力欄も含まれている場合、必須の入力欄を視覚的に示すのを色だけに依存しないようにしてください。通常、説明する文字列やアイコンが使用されます。

仕様書

Specification
HTML
# selector-required
Selectors Level 4
# required-pseudo

ブラウザーの互換性

関連情報