この翻訳は不完全です。英語から この記事を翻訳 してください。

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

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

メモ: HTML5 の制約検証は、サーバー側での検証の必要性をなくす訳ではありません。不正なフォームのリクエストは減少することが期待されるものの、不正なリクエストはまだ互換性のないブラウザー(例えば、 HTML5 や JavaScript に対応していないブラウザー)から送られたり、ウェブアプリケーションをだまそうとする悪意のある人から送られたりする可能性があります。従って、 HTML4 の時と同様、クライアント側で行われている検証と一貫性のある方法で、サーバー側でも入力の制約を検証する必要があります。

組込みの基本的な制約

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

  • <input> 要素の type 属性に意味的に最も適切な値を選択することで、例えば email を選択することで、値が妥当なメールアドレスであるかどうかをチェックする制約が自動的に作成されます。
  • 検証関連属性を設定することで、基本的な制約を簡単な方法で、 JavaScript の必要なく記述できます。

意味を持つ入力型

type 属性の組込み制約は次の通りです。

入力型 制約の説明 関連付けられた違反
<input type="URL"> 値は絶対 URL であり、 URL Living Standard で定義された通りでなければなりません。 Type mismatch 制約違反
<input type="email"> 値は統語的に妥当なメールアドレス、ふつうは username@hostname.tld の書式でなければなりません。 Type mismatch 制約違反

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

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

The following attributes are used to describe basic constraints:

Attribute Input types supporting the attribute Possible values Constraint description Associated violation
pattern text, search, url, tel, email, password A JavaScript regular expression (compiled with the ECMAScript 5 global, ignoreCase, and multiline flags disabled) The value must match the pattern. Pattern mismatch constraint violation
min range, number A valid number The value must be greater than or equal to the value. Underflow constraint violation
date, month, week A valid date
datetime, datetime-local, time A valid date and time
max range, number A valid number The value must be less than or equal to the value Overflow constraint violation
date, month, week A valid date
datetime, datetime-local, time A valid date and time
required text, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file; also on the <select> and <textarea> elements none as it is a Boolean attribute: its presence means true, its absence means false There must be a value (if set). Missing constraint violation
step date An integer number of days Unless the step is set to the any literal, the value must be min + an integral multiple of the step. Step mismatch constraint violation
month An integer number of months
week An integer number of weeks
datetime, datetime-local, time An integer number of seconds
range, number An integer
minlength text, search, url, tel, email, password; also on the <textarea> element An integer length The number of characters (code points) must not be less than the value of the attribute, if non-empty. All newlines are normalized to a single character (as opposed to CRLF pairs) for <textarea>. Too short constraint violation
maxlength text, search, url, tel, email, password; also on the <textarea> element An integer length The number of characters (code points) must not exceed the value of the attribute. Too long constraint violation

制約検証プロセス

Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the <form> element itself. The constraint validation is done in the following ways:

  • By a call to the checkValidity() or reportValidity() method of a form-associated DOM interface, (HTMLInputElement, HTMLSelectElement, HTMLButtonElement, HTMLOutputElement or HTMLTextAreaElement), which evaluates the constraints only on this element, allowing a script to get this information. The checkValidity() method returns a Boolean indicating whether the element's value passes its constraints. (This is typically done by the user-agent when determining which of the CSS pseudo-classes, :valid or :invalid, applies.) In contrast, the reportValidity() method reports any constraint failures to the user.
  • By a call to the checkValidity() or reportValidity() method on the HTMLFormElement interface.
  • By submitting the form itself.

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

Note:
  • If the novalidate attribute is set on the <form> element, interactive validation of the constraints doesn't happen.
  • Calling the submit() method on the HTMLFormElement interface doesn't trigger a constraint validation. In other words, this method sends the form data to the server even if doesn't satisfy the constraints. Call the click() method on a submit button instead.

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

Using JavaScript and the Constraint API, it is possible to implement more complex constraints, for example, constraints combining several fields, or constraints involving complex calculations.

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

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:

<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:

First, we write a function checking the constraint itself:

function checkZIP() {
  // For each country, defines the pattern that the ZIP has to follow
  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" ],
    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" ]
  };
  
  // Read the country id
  var country = document.getElementById("Country").value;

  // Get the NPA field
  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
    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
    ZIPField.setCustomValidity(constraints[country][1]);
  }
}

Then we link it to the onchange event for the <select> and the oninput event for the <input>:

window.onload = function () {
    document.getElementById("Country").onchange = checkZIP;
    document.getElementById("ZIP").oninput = checkZIP;
}

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

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

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.

Here is the HTML part:

<label for="FS">Select a file smaller than 75 kB : </label>
<input type="file" id="FS">

This displays:

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:

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");
       return;
     }
  }
  // No custom constraint violation
  FS.setCustomValidity("");
}

Finally we hook the method with the correct event:

window.onload = function () {
  document.getElementById("FS").onchange = checkFileSize;
}

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.

要素の外見の制御

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

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

The :required and :optional pseudo-classes allow writing selectors that match form elements that have the required attribute, or that don't have it.

CSS の :-moz-placeholder 疑似クラス

See :-moz-placeholder.

CSS の :valid :invalid 疑似クラス

The :valid and :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) method on the following elements:
  • The ValidityState interface describes the object returned by the validity property of the element types listed above. It represents various ways that an entered value can be invalid. Together, they help explain why an element's value fails to validate, if it's not valid.

ドキュメントのタグと貢献者

このページの貢献者: mdnwebdocs-bot, mfuji09
最終更新者: mdnwebdocs-bot,