From 9a6749a0f6831bbead3e2131c28aecc0901be9da Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Mon, 13 Dec 2021 22:31:44 +0900 Subject: 2021/12/13 時点の英語版に同期 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../web/guide/html/constraint_validation/index.md | 506 +++++++++++---------- 1 file changed, 278 insertions(+), 228 deletions(-) (limited to 'files') diff --git a/files/ja/web/guide/html/constraint_validation/index.md b/files/ja/web/guide/html/constraint_validation/index.md index 220df9c79b..3bd4919e47 100644 --- a/files/ja/web/guide/html/constraint_validation/index.md +++ b/files/ja/web/guide/html/constraint_validation/index.md @@ -10,321 +10,371 @@ tags: translation_of: Web/Guide/HTML/Constraint_validation original_slug: Web/Guide/HTML/HTML5/Constraint_validation --- -

ウェブフォームの作成は常に複雑な作業でした。フォーム自体をマークアップすること自体は簡単ですが、それぞれの入力欄が妥当で一貫しているかどうかをチェックすることはもっと難しく、問題をユーザーに伝えることは頭痛がするかもしれません。HTML5 では、フォームに新しい仕組みが導入されました。{{ HTMLElement("input") }} 要素に意味を持つ新しい型と、クライアント側でフォームの内容をチェックする作業を簡単にする制約検証が追加されました。基本的な、よくある制約は、JavaScript を必要とせずに、新しい属性を設定することでチェックできます。もっと複雑な制約は制約検証 API を使用して検査することができます。

+ウェブフォームの作成は常に複雑な作業でした。フォーム自体をマークアップすること自体は簡単ですが、それぞれの入力欄が妥当で一貫しているかどうかをチェックすることはもっと難しく、問題をユーザーに伝えることは頭痛がするかもしれません。[HTML5](/ja/docs/Glossary/HTML5) では、フォームに新しい仕組みが導入されました。 {{ HTMLElement("input") }} 要素に意味を持つ新しい型と、クライアント側でフォームの内容をチェックする作業を簡単にする*制約検証*が追加されました。基本的な、よくある制約は、JavaScript を必要とせずに、新しい属性を設定することでチェックできます。もっと複雑な制約は[制約検証 API](/ja/docs/Web/API/Constraint_validation) を使用して検査することができます。 -

これらの概念の基本的な入門 (サンプル付き) は、フォーム検証チュートリアルをご覧ください。

+これらの概念の基本的な入門 (サンプル付き) は、[フォーム検証チュートリアル](/ja/docs/Learn/Forms/Form_validation)をご覧ください。 -
メモ: HTML5 の制約検証は、サーバー側での検証の必要性をなくす訳ではありません。不正なフォームのリクエストは減少することが期待されるものの、不正なリクエストはまだ互換性のないブラウザー(例えば、HTML5 や JavaScript に対応していないブラウザー)から送られたり、ウェブアプリケーションをだまそうとする悪意のある人から送られたりする可能性があります。従って、HTML4 の時と同様、クライアント側で行われている検証と一貫性のある方法で、サーバー側でも入力の制約を検証する必要があります。
+> **Note:** HTML5 の制約検証は、*サーバー側*での検証の必要性をなくす訳ではありません。不正なフォームのリクエストは減少すると思われますが、不正なリクエストはまだ互換性のないブラウザー(例えば、HTML5 や JavaScript に対応していないブラウザー)から送られたり、ウェブアプリケーションをだまそうとする悪意のある人から送られたりする可能性があります。従って、HTML4 の時と同様、クライアント側で行われている検証と一貫性のある方法で、サーバー側でも入力の制約を検証する必要があります。 -

組込みの基本的な制約

+## 組み込みの基本的な制約 -

HTML5 では、基本的な制約は 2通りの方法で定義されます。

+HTML5 では、基本的な制約は 2 通りの方法で定義されます。 - +- {{ HTMLElement("input") }} 要素の {{ htmlattrxref("type", "input") }} 属性に意味的に最も適切な値を選択する。例えば `email` を選択することで、値が妥当なメールアドレスであるかどうかをチェックする制約が自動的に作成されます。 +- 検証関連属性を設定することで、基本的な制約を簡単な方法で、JavaScript の必要なく記述できます。 -

意味を持つ入力型

+### 意味を持つ入力型 -

{{ htmlattrxref("type", "input") }} 属性の組込み制約は次の通りです。

+{{ htmlattrxref("type", "input") }} 属性の組込み制約は次の通りです。 - - - - - - - - - - - - - - - - - - - - -
入力型制約の説明関連付けられた違反
<input type="URL">値は絶対 URL であり、URL Living Standard で定義された通りでなければなりません。TypeMismatch 制約違反
<input type="email">値は統語的に妥当なメールアドレス、ふつうは username@hostname.tld の書式でなければなりません。TypeMismatch 制約違反
+| 入力型 | 制約の説明 | 関連付けられた違反 | +| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| [``](/ja/docs/Web/HTML/Element/input/url) | 値は絶対 [URL](/ja/docs/Learn/Common_questions/What_is_a_URL) であり、 [URL Living Standard](https://url.spec.whatwg.org/) で定義された通りでなければなりません。 | **[TypeMismatch](/ja/docs/Web/API/ValidityState/typeMismatch)** 制約違反 | +| [``](/ja/docs/Web/HTML/Element/input/email) | 値は統語的に妥当なメールアドレスで、ふつうは `username@hostname.tld` の書式でなければなりません。 | **[TypeMismatch](/ja/docs/Web/API/ValidityState/typeMismatch)** 制約違反 | -

これらの入力型のどちらでも、{{ htmlattrxref("multiple", "input") }} 属性が設定されていたら、この入力欄にカンマ区切りのリストで複数の値を設定することができます。これらの中でここで書かれた条件に満足しないものがある場合、Type mismatch 制約違反が発生します。

+これらの入力型のどちらでも、{{ htmlattrxref("multiple", "input") }} 属性が設定されていたら、この入力欄にカンマ区切りのリストで複数の値を設定することができます。これらの中でここで書かれた条件に満足しないものがある場合、 **Type mismatch** 制約違反が発生します。 -

なお、ほとんどの入力型には組込み制約がありません。制約検証によって防ぐことができたり、既定で不正な値を妥当な値に変換する無害化アルゴリズムがあったりするためです。

+なお、ほとんどの入力型には内部的な制約がありません。制約検証が禁止されているものや、不正な値を正しい既定値に変換する無害化アルゴリズムがあるものがあるためです。 - +### 検証関連属性 -

上記で述べた type 属性に加えて、下記の要素が基本的な制約を記述するのに使われます。

+上記で述べた `type` 属性に加えて、下記の要素が基本的な制約を記述するのに使われます。 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性属性をサポートする入力タイプとりうる値制約の説明関連する違反
patterntext, search, url, tel, email, passwordJavaScript 正規表現 (ECMAScript 5 global, ignoreCasemultiline フラグが無効でコンパイルされたもの)値はパターンに一致する必要があります。patternMismatch 制約違反
minrange, number有効な数値値以上であること。rangeUnderflow 制約違反
date, month, week有効な日付
datetime, datetime-local, time有効な日付と時刻
maxrange, number有効な数値値以下であること。rangeOverflow 制約違反
date, month, week有効な日付
datetime, datetime-local, time有効な日付と時刻
requiredtext, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file; {{ HTMLElement("select") }} と {{ HTMLElement("textarea") }} 要素にも。none Boolean 属性のため: 存在すれば true, 存在しなければ false値は必須 (セットされた場合)。valueMissing 制約違反
stepdate日の整数値step がリテラル値 any にセットされていない場合、値は min + step の整数倍stepMismatch 制約違反
month月の整数値
week週の整数値
datetime, datetime-local, time秒の整数値
range, number整数値
minlengthtext, search, url, tel, email, password; と {{ HTMLElement("textarea") }} 要素整数長文字列数 (code points) は、空でない場合は属性値より少なくならない。{{ HTMLElement("textarea") }}では改行はすべて 1 つの文字に正規化される (CRLF の組と対象的に)。tooShort 制約違反
maxlengthtext, search, url, tel, email, password; と {{ HTMLElement("textarea") }} 要素整数長文字列数 (code points) は属性値を超えない。tooLong 制約違反
属性属性をサポートする入力型とりうる値制約の説明関連する違反
+ pattern + + text, search, url, + tel, email, password + + JavaScript 正規表現 + (ECMAScript 5global, ignoreCase, multiline フラグが無効でコンパイルされたもの) + 値がパターンに一致する必要がある。 + patternMismatch + 制約違反 +
+ min + range, number有効な数値値がその値以上であること。 + rangeUnderflow + 制約違反 +
date, month, week有効な日付
+ datetime, datetime-local, time + 有効な日付と時刻
+ max + range, number有効な数値値がその値以下であること。 + rangeOverflow + 制約違反 +
date, month, week有効な日付
+ datetime, datetime-local, time + 有効な日付と時刻
+ required + + text, search, url, + tel, email, password, + date, datetime, datetime-local, + month, week, time, + number, checkbox, radio, + file および {{ HTMLElement("select") }} と {{ HTMLElement("textarea") }} 要素にも + + なし。論理属性のため、存在すれば true、存在しなければ false を意味する。 + 値は必須 (設定された場合)。 + valueMissing + 制約違反 +
+ step + date日の整数値 + step がリテラル値 any 以外に設定されていた場合、値は min + step の整数倍である必要がある。 + + stepMismatch + 制約違反 +
month月の整数値
week週の整数値
+ datetime, datetime-local, time + 秒の整数値
range, number整数値
+ minlength + + text, search, url, + tel, email, password と + {{ HTMLElement("textarea") }} 要素 + 整数長 + 空でない場合、文字数 (コードポイント数) は属性値より少なくなってはならない。 {{ HTMLElement("textarea") }} では、改行はすべて (CRLF の組ではなく) 1 文字に正規化される。 + + tooShort + 制約違反 +
+ maxlength + + text, search, url, + tel, email, password と + {{ HTMLElement("textarea") }} 要素 + 整数長 + 文字数 (コードポイント数) が属性値を超えてはいけない。 + + tooLong + 制約違反 +
-

制約検証プロセス

+## 制約検証プロセス -

Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the {{ HTMLElement("form") }} element itself. The constraint validation is done in the following ways:

+制約検証は、制約検証 API を通じて、単一のフォーム要素、またはフォームレベルの {{ HTMLElement("form") }} 要素自体に対して行われます。制約検証は以下の方法で行われます。 - +- `checkValidity()` または `reportValidity()` メソッドをフォーム関連 DOM インターフェイス ([`HTMLInputElement`](/ja/docs/Web/API/HTMLInputElement), [`HTMLSelectElement`](/ja/docs/Web/API/HTMLSelectElement), [`HTMLButtonElement`](/ja/docs/Web/API/HTMLButtonElement), [`HTMLOutputElement`](/ja/docs/Web/API/HTMLOutputElement), [`HTMLTextAreaElement`](/ja/docs/Web/API/HTMLTextAreaElement)) に対して呼び出すことによって、この要素のみの制約を評価し、スクリプトがこの情報を取得できるようにします。 `checkValidity()` メソッドは、この要素の値が制約に合格するかどうかを論理値で返します。(これはふつう、 CSS 擬似クラスの {{ Cssxref(":valid") }} または {{ Cssxref(":invalid") }} のどちらを適用するかを判断する際に、ブラウザーが呼び出します。)一方、 `reportValidity()` メソッドはあらゆる制約違反をユーザーに報告します。 +- `checkValidity()` または `reportValidity()` メソッドを [`HTMLFormElement`](/ja/docs/Web/API/HTMLFormElement) インターフェイスに対して呼び出すことによって。 +- フォーム自身を送信することによって。 -

Calling checkValidity() is called statically validating the constraints, while calling reportValidity() or submitting the form is called interactively validating the constraints.

+`checkValidity()` を呼び出すことは、制約を*静的*に検証するといい、`reportValidity()` を呼び出したり、フォームを送信したりすることは、制約を*対話的*に検証するといいます。 -
Note: +> **Note:** +> +> - {{ htmlattrxref("novalidate", "form") }} 属性が {{ HTMLElement("form") }} 要素に設定されている場合、制約の*対話的*な検証は行われません。 +> - `submit()` メソッドを [`HTMLFormElement`](/ja/docs/Web/API/HTMLFormElement) インターフェイスで呼び出しても、制約検証は行われません。言い換えれば、このメソッドは制約を満たさなくてもフォームデータをサーバーに送信します。代わりに送信ボタンの `click()` メソッドを呼び出してください。 - -
+## 制約検証 API を使用した複雑な制約 -

HTML5 制約 API を使用した複雑な制約

+JavaScript と制約 API を使用すると、より複雑な制約を実装することができます。例えば、複数のフィールドを組み合わせた制約や、複雑な計算を含む制約などです。 -

Using JavaScript and the Constraint API, it is possible to implement more complex constraints, 例えば、constraints combining several fields, or constraints involving complex calculations.

+基本的には、制約に違反しているかどうかを計算するために、何らかのフォームフィールドイベント (**onchange**など) で JavaScript を起動し、検証の結果を設定するためにメソッド `field.setCustomValidity()` を使用することです。空文字列は制約が満たされていることを意味し、その他の文字列はエラーがあったことを意味し、この文字列がユーザーに表示するエラーメッセージになります。 -

Basically, the idea is to trigger JavaScript on some form field event (like onchange) to calculate whether the constraint is violated, and then to use the method field.setCustomValidity() to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an error and this string is the error message to display to the user.

+### 複数のフィールドを組み合わせた制約:郵便番号の検証 -

Constraint combining several fields: Postal code validation

+郵便番号の形式は、国によって異なります。ほとんどの国では、国コードの前に任意の接頭辞を付けることができるだけでなく(ドイツでは `D-`、フランスやスイスでは `F-` のように)、固定の桁数しかない郵便番号を持つ国もありますし、イギリスのように、特定の位置にアルファベットを入れることができる、より複雑な構造を持つ国もあります。 -

The postal code format varies from one country to another. Not only do most countries allow an optional prefix with the country code (like D- in Germany, F- in France or Switzerland), but some countries have postal codes with only a fixed number of digits; others, like the UK, have more complex structures, allowing letters at some specific positions.

+> **Note:** これは包括的な郵便番号検証ライブラリーではなく、主要概念のデモンストレーションです。 -
-

注: This is not a comprehensive postal code validation library, but rather a demonstration of the key concepts.

-
+例として、この単純なフォームの制約検証をチェックするスクリプトを追加します。 -

As an example, we will add a script checking the constraint validation for this simple form:

+```html +
+ + + + + +
+``` -
<form>
-    <label for="ZIP">ZIP : </label>
-    <input type="text" id="ZIP">
-    <label for="Country">Country : </label>
-    <select id="Country">
-      <option value="ch">Switzerland</option>
-      <option value="fr">France</option>
-      <option value="de">Germany</option>
-      <option value="nl">The Netherlands</option>
-    </select>
-    <input type="submit" value="Validate">
-</form>
+これは以下のように表示されます。 -

This displays the following form:

+{{EmbedLiveSample("Constraint_combining_several_fields_Postal_code_validation")}} -

{{EmbedLiveSample("Constraint_combining_several_fields_Postal_code_validation")}}

+まず、自分自身の制約をチェックする関数を書きます。 -

First, we write a function checking the constraint itself:

- -
function checkZIP() {
-  // For each country, defines the pattern that the ZIP has to follow
+```js
+function checkZIP() {
+  // それぞれの国で、郵便番号が従うべきパターンを定義する
   var constraints = {
-    ch : [ '^(CH-)?\\d{4}$', "Switzerland ZIPs must have exactly 4 digits: e.g. CH-1950 or 1950" ],
-    fr : [ '^(F-)?\\d{5}$' , "France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012" ],
-    de : [ '^(D-)?\\d{5}$' , "Germany ZIPs must have exactly 5 digits: e.g. D-12345 or 12345" ],
+    ch : [ '^(CH-)?\\d{4}$', "スイスの郵便番号は明確な 4 桁である必要があります。例: CH-1950 または 1950" ],
+    fr : [ '^(F-)?\\d{5}$' , "フランスの郵便番号は明確な 5 桁です。例: F-75012 または 75012" ],
+    de : [ '^(D-)?\\d{5}$' , "ドイツの郵便番号は明確な 5 桁です。例: D-12345 または 12345" ],
     nl : [ '^(NL-)?\\d{4}\\s*([A-RT-Z][A-Z]|S[BCE-RT-Z])$',
-                    "Nederland ZIPs must have exactly 4 digits, followed by 2 letters except SA, SD and SS" ]
+                    "オランダの郵便番号は明確な 4 桁に、SA、SD、SS 以外の2文字が続きます。" ]
   };
 
-  // Read the country id
+  // 国 ID を読む
   var country = document.getElementById("Country").value;
 
-  // Get the NPA field
+  // NPA フィールドを取得
   var ZIPField = document.getElementById("ZIP");
 
-  // Build the constraint checker
+  // 制約チェッカーを構築
   var constraint = new RegExp(constraints[country][0], "");
     console.log(constraint);
 
-
-  // Check it!
+  // チェックする
   if (constraint.test(ZIPField.value)) {
-    // The ZIP follows the constraint, we use the ConstraintAPI to tell it
+    // 郵便番号は制約に従っていることを ConstraintAPI を使って伝える
     ZIPField.setCustomValidity("");
   }
   else {
-    // The ZIP doesn't follow the constraint, we use the ConstraintAPI to
-    // give a message about the format required for this country
+    // 郵便番号が制約に従っていないことを伝えるために、 ConstraintAPI を使用して
+    // この国で必要な書式についてのメッセージを伝える
     ZIPField.setCustomValidity(constraints[country][1]);
   }
 }
-
+``` -

Then we link it to the onchange event for the {{ HTMLElement("select") }} and the oninput event for the {{ HTMLElement("input") }}:

+それから、これを {{ HTMLElement("select") }} の **onchange** イベントと {{ HTMLElement("input") }} の **oninput** イベントにリンクします。 -
window.onload = function () {
+```js
+window.onload = function () {
     document.getElementById("Country").onchange = checkZIP;
     document.getElementById("ZIP").oninput = checkZIP;
-}
+} +``` -

You can see a live example of the postal code validation.

+郵便番号の検証の[ライブサンプル](/@api/deki/files/4744/=constraint.html)もあります。 -

アップロード前のファイルサイズの制限

+### アップロード前にファイルの大きさを制限 -

Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint Validation API, and especially the field.setCustomValidity() method, with another JavaScript API, here the File API.

+もう一つの一般的な制約は、アップロードされるファイルのサイズを制限することです。ファイルがサーバーに送信される前に、クライアント側でこれをチェックするには、制約検証 API、特に `field.setCustomValidity()` メソッドを、別の JavaScript API、ここでは File API と組み合わせる必要があります。 -

Here is the HTML part:

+こちらが HTML 部分です。 -
<label for="FS">Select a file smaller than 75 kB : </label>
-<input type="file" id="FS">
+```html + + +``` -

This displays:

+次のように表示されます。 -

{{EmbedLiveSample("Limiting_the_size_of_a_file_before_its_upload")}}

+{{EmbedLiveSample("Limiting_the_size_of_a_file_before_its_upload")}} -

The JavaScript reads the file selected, uses the File.size() method to get its size, compares it to the (hard coded) limit, and calls the Constraint API to inform the browser if there is a violation:

+JavaScript は選択されたファイルを読み込み、 `File.size()` メソッドを使ってそのサイズを取得し、それを(ハードコードされた)制限値と比較し、違反があった場合は Constraint API を呼び出してブラウザーに通知します。 -
function checkFileSize() {
+```js
+function checkFileSize() {
   var FS = document.getElementById("FS");
   var files = FS.files;
 
   // If there is (at least) one file selected
-  if (files.length > 0) {
-     if (files[0].size > 75 * 1024) { // Check the constraint
-       FS.setCustomValidity("The selected file must not be larger than 75 kB");
+  if (files.length > 0) {
+     if (files[0].size > 75 * 1024) { // 制約をチェック
+       FS.setCustomValidity("選択されたファイルは 75 kB より大きくてはいけません。");
        return;
      }
   }
   // No custom constraint violation
   FS.setCustomValidity("");
-}
+} +``` -

Finally we hook the method with the correct event:

+最後に、このメソッドを正しいイベントにフックします。 -
window.onload = function () {
+```js
+window.onload = function () {
   document.getElementById("FS").onchange = checkFileSize;
-}
+} +``` + +ファイルサイズの制約検証の[ライブサンプル](/@api/deki/files/4745/=fileconstraint.html)を見ることができます。 -

You can see a live example of the File size constraint validation.

+## 制約検証の視覚的スタイル -

制約検証における表示の整形

+制約条件を設定するだけでなく、ウェブ開発者は、ユーザーにどのようなメッセージを表示するか、どのようなスタイルにするかを制御したいと考えています。 -

Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled.

+### 要素の外見の制御 -

要素の外見の制御

+CSS の擬似クラスで、要素の外見を制御することができます。 -

The look of elements can be controlled via CSS pseudo-classes.

+#### :required および :optional 擬似クラス -

CSS の :required および :optional 疑似クラス

+{{cssxref(':required')}} と {{cssxref(':optional')}} [擬似クラス](/ja/docs/Web/CSS/Pseudo-classes)で、 {{ htmlattrxref("required") }} 属性がある、またはないフォーム要素に一致するセレクターを書くことができます。 -

The {{cssxref(':required')}} and {{cssxref(':optional')}} pseudo-classes allow writing selectors that match form elements that have the {{ htmlattrxref("required") }} attribute, or that don't have it.

+#### :placeholder-shown 擬似クラス -

:placeholder-shown CSS pseudo-class

+{{cssxref(':placeholder-shown')}} を参照してください。 -

See {{cssxref(':placeholder-shown')}}

+#### :valid :invalid 擬似クラス -

CSS の :valid :invalid 疑似クラス

+{{cssxref(':valid')}} と {{cssxref(':invalid')}} [擬似クラス](/ja/docs/Web/CSS/Pseudo-classes)は、 \ 要素の内容がその型の設定に応じて、それぞれ検証されたか、検証に失敗したかを表すために使用します。これらのクラスは、有効または無効なフォーム要素にスタイルを与えることで書式が正しい要素と正しくない要素の識別をしやすくします。 -

The {{cssxref(':valid')}} and {{cssxref(':invalid')}} pseudo-classes are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly.

+### 制約違反のテキストの制御 -

制約違反の文字列の制御

+制約違反のテキストを制御するには、以下の項目が有用です。 -

The following items can help with controlling the text of a constraint violation:

+- 以下の要素の [element.setCustomValidity(message)]() メソッド - +- [`ValidityState`](/ja/docs/Web/API/ValidityState) インターフェイスは、上記の要素型の [validity](/ja/docs/Web/API/Constraint_validation#validity) プロパティによって返されるオブジェクトを説明します。入力された値が無効になる可能性がある様々な方法を表しています。これらを合わせると、要素の値が有効でない場合に、なぜ検証に失敗するのかを説明することができます。 -- cgit v1.2.3-54-g00ecf