From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../ru/html/html5/constraint_validation/index.html | 343 +++++++++++++++++++++ 1 file changed, 343 insertions(+) create mode 100644 files/ru/html/html5/constraint_validation/index.html (limited to 'files/ru/html/html5/constraint_validation/index.html') diff --git a/files/ru/html/html5/constraint_validation/index.html b/files/ru/html/html5/constraint_validation/index.html new file mode 100644 index 0000000000..5a5fccec8c --- /dev/null +++ b/files/ru/html/html5/constraint_validation/index.html @@ -0,0 +1,343 @@ +--- +title: Constraint validation +slug: HTML/HTML5/Constraint_validation +tags: + - Селекторы +translation_of: Web/Guide/HTML/HTML5/Constraint_validation +--- +

Создание веб форм всегда было комплексной задачей. В то время как сама по себе разметка формы - задача не сложная, проверка каждого поля на валидность - сложнее, а информирование юзера о проблеме - может стать головной болью. Стандарт HTML5 предоставил новые механизмы для форм: были добавлены новые семантические типы для элемента {{ HTMLElement("input") }} и обязательная валидация, чтобы облегчить работу по проверке содержимого формы на стороне браузера. Проще говоря, обычная проверка может быть выполнена без JavaScript, простой установкой новых аттрибутов; более сложные ограничения могут быть реализованы через HTML5 Constraint Validation API.

+ +
Внимание: HTML5 Constraint validation не отменяет валидацию на стороне сервера. Несмотря на то что на сервер будет отправляться меньше запросов с невалидными данными, такие запросы всё ещё могут быть отправлены менее "сговорчивыми" браузерами (например, браузерами без поддержки HTML5 и без JavaScript) или плохими парнями, пытающимися взломать ваше веб-приложение. Следовательно, как и в случае с HTML4, вам всё ещё нужно проверять ввод на стороне сервера, таким образом, чтобы это было согласовано с валидацией на стороне клиента.
+ +

Внутренние и базовые ограничения

+ +

В HTML5, базовые ограничения описываются двумя способами:

+ + + +

Семантические типы input-ов

+ +

Аттрибуты, присущие элементам {{ htmlattrxref("type", "input") }}:

+ + + + + + + + + + + + + + + + + + + + + +
Input typeОпределение ограниченияСвязанное с этим нарушение
<input type="URL">Значение должно быть абсолютным URL, одним из: +
    +
  • валидным URI (как описано в RFC 3986)
  • +
  • валидным IRI, без query сомпонента (как описано в RFC 3987)
  • +
  • валидным IRI, без query сомпонента и без неэкранированных не-ASCII символов (как описано в RFC 3987)
  • +
  • валидным IRI, при условии, что кодировка документа UTF-8 или UTF-16 (как описано в RFC 3987)
  • +
+
Type mismatch constraint violation
 <input type="email">Значение должно следовать ABNF: 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str ) где: +
    +
  • atext (описан в RFC 5322) - US-ASCII символ (A to Z and a-z), цифра (от 0 до 9) или один из следующих: 
    + ! # $ % & ' * + - / = ? ` { } | ~ специальных символов,
  • +
  • ldh-str (описан в RFC 1034) - US-ASCII символы, цифры и "-", сгруппированы по словам и разделённые точкой (.).
  • +
+ +
Внимание: если установлен аттрибут {{ htmlattrxref("multiple", "input") }}, в поле могут быть вписаны несколько e-mail адресов, разделённых запятыми. Если любое из этих условий не выполнено, будет вызвано Type mismatch constraint violation.
+
Type mismatch constraint violation
+ +

Следует учесть, что большинство типов input не имеют "нативных" ограничений, а некоторые из них просто лишены валидации или имеют автоматическую корректировку невалидных значений по умолчанию. 

+ +

Аттрибуты валидации

+ +

Ниже перечислены аттрибуты, которые описывают базовые ограничения:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
АттрибутТипы input с поддержкой аттрибутаВозможные значенияОписание ограниченияСвязанное нарушение
{{ htmlattrxref("pattern", "input") }}text, search, url, tel, email, passwordРегулярное выражение JavaScript (по стандарту ECMAScript 5, флаги global, ignoreCase, и multiline отключены)Значение должно подходить под паттернPattern mismatch constraint violation
{{ htmlattrxref("min", "input") }}range, numberВалидное числоЗначение поля должно быть больше или равно значению аттрибутаUnderflow constraint violation
date, month, weekВалидная дата
datetime, datetime-local, timeВалидная дата и время
{{ htmlattrxref("max", "input") }}range, numberВалидное числоЗначение поля должно быть меньше или равно значению аттрибутаOverflow constraint violation
date, month, weekВалидная дата
datetime, datetime-local, timeВалидная дата и время
{{ htmlattrxref("required", "input") }}text, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file; also on the {{ HTMLElement("select") }} and {{ HTMLElement("textarea") }} elementsникакое так как это Boolean аттрибут: его присутствие означает true, а отсутствие - falseЗначение должно быть не пустым (если установлено).Missing constraint violation
{{ htmlattrxref("step", "input") }}dateЦелое число днейПока в аттрибут step не установлен любой литерал, значение может быть min + любое число, крастное шагу.Step mismatch constraint violation
monthЦелое число месяцев
weekЦелое число недель
datetime, datetime-local, timeЦелое число секунд
range, numberЦелое число
{{ htmlattrxref("maxlength", "input") }}text, search, url, tel, email, password; также на элементе {{ HTMLElement("textarea") }}Длина (целое число)Количество символов (знаков) не должно превышать значение аттрибута.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 {{ HTMLElement("form") }} element itself. The constraint validation is done in the following ways:

+ + + +
Note: + + +
+ +

Complex constraints using HTML5 Constraint 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 {{ HTMLElement("select") }} and the oninput event for the {{ HTMLElement("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.  

+ +

Limiting the size of a file before its upload

+ +

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 API, and especially the field.setCustomValidity() method, with another JavaScript API, here the HTML5 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.

+ +

Visual styling of constraint validation

+ +

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

+ +

Controlling the look of elements

+ +

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

+ +

:required and :optional CSS pseudo-classes

+ +

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

+ + +

:-moz-placeholder CSS pseudo-class

+ +

See :-moz-placeholder.

+ +

:valid :invalid CSS pseudo-classes

+ +

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.

+ +

Default styles

+ +

Controlling the text of constraints violation

+ +

The x-moz-errormessage attribute

+ +

The x-moz-errormessage attribute is a Mozilla extension that allows you to specify the error message to display when a field does not successfully validate.

+ +
+

Note: This extension is non-standard.

+
+ +

Constraint API's element.setCustomValidity()

+ +

The element.setCustomValidity(error) method is used to set a custom error message to be displayed when a form is submitted. The method works by taking a string parameter error. If error is a non-empty string, the method assumes validation was unsuccessful and displays error as an error message. If error is an empty string, the element is considered validated and resets the error message.

+ +

Constraint API's ValidityState object

+ +

The DOM ValidityState interface represents the validity states that an element can be in, with respect to constraint validation. Together, they help explain why an element's value fails to validate, if it's not valid.

+ +

Examples of personalized styling

+ +

HTML4 fallback

+ +

Trivial fallback

+ +

JS fallback

+ +

Conclusion

-- cgit v1.2.3-54-g00ecf