diff options
Diffstat (limited to 'files/ru/web/guide/html/html5/constraint_validation/index.html')
-rw-r--r-- | files/ru/web/guide/html/html5/constraint_validation/index.html | 342 |
1 files changed, 0 insertions, 342 deletions
diff --git a/files/ru/web/guide/html/html5/constraint_validation/index.html b/files/ru/web/guide/html/html5/constraint_validation/index.html deleted file mode 100644 index 73be6d59bb..0000000000 --- a/files/ru/web/guide/html/html5/constraint_validation/index.html +++ /dev/null @@ -1,342 +0,0 @@ ---- -title: Constraint validation -slug: Web/Guide/HTML/HTML5/Constraint_validation -tags: - - Селекторы -translation_of: Web/Guide/HTML/HTML5/Constraint_validation -original_slug: HTML/HTML5/Constraint_validation ---- -<p>Создание веб форм всегда было комплексной задачей. В то время как сама по себе разметка формы - задача не сложная, проверка каждого поля на валидность - сложнее, а информирование пользователя о проблеме - может стать головной болью. Стандарт <a href="/en-US/docs/Web/Guide/HTML/HTML5" title="en/HTML/HTML5">HTML5</a> предоставил новые механизмы для форм: были добавлены новые семантические типы для элемента {{ HTMLElement("input") }} и <em>обязательная валидация, </em>чтобы облегчить работу по проверке содержимого формы на стороне браузера. Проще говоря, обычная проверка может быть выполнена без JavaScript, простой установкой новых атрибутов; более сложные ограничения могут быть реализованы через HTML5 <a href="/en-US/docs/Web/Guide/HTML/Forms_in_HTML#Constraint_Validation_API" title="en/HTML/HTML5/Forms in HTML5#Constraint Validation API">Constraint Validation API</a>.</p> - -<div class="note"><strong>Внимание:</strong> HTML5 Constraint validation не отменяет валидацию <em>на стороне сервера</em>. Несмотря на то что на сервер будет отправляться меньше запросов с невалидными данными, такие запросы всё ещё могут быть отправлены менее "сговорчивыми" браузерами (например, браузерами без поддержки HTML5 и без JavaScript) или плохими парнями, пытающимися взломать ваше веб-приложение. Следовательно, как и в случае с HTML4, вам всё ещё нужно проверять ввод на стороне сервера, таким образом, чтобы это было согласовано с валидацией на стороне клиента.</div> - -<h2 id="Внутренние_и_базовые_ограничения">Внутренние и базовые ограничения</h2> - -<p>В HTML5, базовые ограничения описываются двумя способами:</p> - -<ul> - <li>Использованием наиболее семантически подходящего значения для {{ htmlattrxref("type", "input") }} атрибута элемента {{ HTMLElement("input") }}, например, выбор типа <span style="font-family: courier new;">email</span> автоматически создаёт ограничение, которое проверяет, является ли значение e-mail адресом.</li> - <li>Установкой значений для атрибутов, связанных с валидацией, описывая базовые ограничения без использования JavaScript.</li> -</ul> - -<h3 id="Семантические_типы_input-ов">Семантические типы input-ов</h3> - -<p>Атрибуты, присущие элементам {{ htmlattrxref("type", "input") }}:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Input type</th> - <th scope="col">Определение ограничения</th> - <th scope="col">Связанное с этим нарушение</th> - </tr> - </thead> - <tbody> - <tr> - <td><span style="font-family: courier new;"><input type="URL"></span></td> - <td>Значение должно быть абсолютным URL, одним из: - <ul> - <li>валидным URI (как описано в <a class="external" href="http://www.ietf.org/rfc/rfc3986.txt" title="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>)</li> - <li>валидным IRI, без query компонента (как описано в <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li> - <li>валидным IRI, без query компонента и без неэкранированных не-ASCII символов (как описано в <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li> - <li>валидным IRI, при условии, что кодировка документа UTF-8 или UTF-16 (как описано в <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li> - </ul> - </td> - <td><strong>Type mismatch </strong>constraint violation</td> - </tr> - <tr> - <td> <span style="font-family: courier new;"><input type="email"></span></td> - <td>Значение должно следовать <a class="external" href="http://www.ietf.org/rfc/std/std68.txt" title="http://www.ietf.org/rfc/std/std68.txt">ABNF</a>: <code>1*( atext / "." ) "@" ldh-str 1*( "." ldh-str )</code> где: - <ul> - <li><code>atext</code> (описан в <a class="external" href="http://tools.ietf.org/html/rfc5322" title="http://tools.ietf.org/html/rfc5322">RFC 5322</a>) - US-ASCII символ (<span style="font-family: courier new;">A</span> to <span style="font-family: courier new;">Z</span> and <span style="font-family: courier new;">a</span>-<span style="font-family: courier new;">z</span>), цифра (от <span style="font-family: courier new;">0</span> до <span style="font-family: courier new;">9</span>) или один из следующих: <br> - <span style="font-family: courier new;">! # $ % & ' * + - / = ? ` { } | ~ </span>специальных символов,</li> - <li><code>ldh-str</code> (описан в <a class="external" href="http://www.apps.ietf.org/rfc/rfc1034.html#sec-3.5" title="http://www.apps.ietf.org/rfc/rfc1034.html#sec-3.5">RFC 1034</a>) - US-ASCII символы, цифры и "<span style="font-family: courier new;">-"</span>, сгруппированы по словам и разделённые точкой (<span style="font-family: courier new;">.</span>).</li> - </ul> - - <div class="note"><strong>Внимание:</strong> если установлен атрибут {{ htmlattrxref("multiple", "input") }}, в поле могут быть вписаны несколько e-mail адресов, разделённых запятыми. Если любое из этих условий не выполнено, будет вызвано <strong>Type mismatch </strong>constraint violation.</div> - </td> - <td><strong>Type mismatch </strong>constraint violation</td> - </tr> - </tbody> -</table> - -<p>Следует учесть, что большинство типов input не имеют "нативных" ограничений, а некоторые из них просто лишены валидации или имеют автоматическую корректировку невалидных значений по умолчанию. </p> - -<h3 id="Атрибуты_валидации">Атрибуты валидации</h3> - -<p>Ниже перечислены атрибуты, которые описывают базовые ограничения:</p> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Атрибут</th> - <th scope="col">Типы input с поддержкой атрибута</th> - <th scope="col">Возможные значения</th> - <th scope="col">Описание ограничения</th> - <th scope="col">Связанное нарушение</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{ htmlattrxref("pattern", "input") }}</td> - <td>text, search, url, tel, email, password</td> - <td><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" title="https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions">Регулярное выражение JavaScript</a> (по стандарту <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" title="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript 5</a>, флаги <code title="">global</code>, <code title="">ignoreCase</code>, и <code title="">multiline</code> <em>отключены)</em></td> - <td>Значение должно подходить под паттерн</td> - <td><strong>Pattern mismatch</strong> constraint violation</td> - </tr> - <tr> - <td rowspan="3">{{ htmlattrxref("min", "input") }}</td> - <td>range, number</td> - <td>Валидное число</td> - <td rowspan="3">Значение поля должно быть больше или равно значению атрибута</td> - <td rowspan="3"><strong>Underflow</strong> constraint violation</td> - </tr> - <tr> - <td>date, month, week</td> - <td>Валидная дата</td> - </tr> - <tr> - <td>datetime, datetime-local, time</td> - <td>Валидная дата и время</td> - </tr> - <tr> - <td rowspan="3">{{ htmlattrxref("max", "input") }}</td> - <td>range, number</td> - <td>Валидное число</td> - <td rowspan="3">Значение поля должно быть меньше или равно значению атрибута</td> - <td rowspan="3"><strong>Overflow</strong> constraint violation</td> - </tr> - <tr> - <td>date, month, week</td> - <td>Валидная дата</td> - </tr> - <tr> - <td>datetime, datetime-local, time</td> - <td>Валидная дата и время</td> - </tr> - <tr> - <td>{{ htmlattrxref("required", "input") }}</td> - <td>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</td> - <td><em>никакое</em> так как это Boolean атрибут: его присутствие означает <em>true</em>, а отсутствие - <em>false</em></td> - <td>Значение должно быть не пустым (если установлено).</td> - <td><strong>Missing</strong> constraint violation</td> - </tr> - <tr> - <td rowspan="5">{{ htmlattrxref("step", "input") }}</td> - <td>date</td> - <td>Целое число дней</td> - <td rowspan="5">Пока в атрибут <code>step</code> не установлен <em>любой</em> литерал, значение может быть <strong>min</strong> + любое число, красное шагу.</td> - <td rowspan="5"><strong>Step mismatch </strong>constraint violation</td> - </tr> - <tr> - <td>month</td> - <td>Целое число месяцев</td> - </tr> - <tr> - <td>week</td> - <td>Целое число недель</td> - </tr> - <tr> - <td>datetime, datetime-local, time</td> - <td>Целое число секунд</td> - </tr> - <tr> - <td>range, number</td> - <td>Целое число</td> - </tr> - <tr> - <td>{{ htmlattrxref("maxlength", "input") }}</td> - <td>text, search, url, tel, email, password; также на элементе {{ HTMLElement("textarea") }}</td> - <td>Длина (целое число)</td> - <td>Количество символов (знаков) не должно превышать значение атрибута.</td> - <td><strong>Too long</strong> constraint violation</td> - </tr> - </tbody> -</table> - -<h2 id="Процесс_валидации_ограничений"><span class="author-g-by4vjwmiwjiydpj7">Процесс валидации ограничений</span></h2> - -<p>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:</p> - -<ul> - <li>By a call to the checkValidity() method of a form-related <a href="/en-US/docs/DOM" title="en/DOM">DOM</a> interface (<code><a href="/en-US/docs/Web/API/HTMLInputElement" title="en/DOM/HTMLInputElement">HTMLInputElement</a></code>, <code><a href="/en-US/docs/Web/API/HTMLSelectElement" title="en/DOM/HTMLSelectElement">HTMLSelectElement</a></code>, <code><a href="/en-US/docs/Web/API/HTMLButtonElement" title="en/DOM/HTMLButtonElement">HTMLButtonElement</a></code> or <code><a href="/en-US/docs/Web/API/HTMLTextAreaElement" title="en/DOM/HTMLTextAreaElement">HTMLTextAreaElement</a></code>), which evaluates the constraints only on this element, allowing a script to get this information. (This is typically done by the user-agent when determining which of the <a href="/en-US/docs/Web/CSS" title="en/CSS">CSS</a> pseudo-classes, {{ Cssxref(":valid") }} or {{ Cssxref(":invalid") }}, applies.)</li> - <li>By a call to the checkValidity() function on the <code><a href="/en-US/docs/Web/API/HTMLFormElement" title="en/DOM/HTMLFormElement">HTMLFormElement</a></code> interface, which is called <em>statically validating the constraints</em>.</li> - <li>By submitting the form itself, which is called <em>interactively validating the constraints</em>.</li> -</ul> - -<div class="note"><strong>Note: </strong> - -<ul> - <li>If the {{ htmlattrxref("novalidate", "form") }} attribute is set on the {{ HTMLElement("form") }} element, interactive validation of the constraints doesn't happen.</li> - <li>Calling the send() method on the <a href="/en/DOM/HTMLFormElement" title="en/DOM/HTMLFormElement">HTMLFormElement</a> 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.</li> -</ul> -</div> - -<h2 id="Complex_constraints_using_HTML5_Constraint_API"><span class="author-g-by4vjwmiwjiydpj7">Complex constraints using HTML5 Constraint API</span></h2> - -<p><span class="author-g-by4vjwmiwjiydpj7">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.</span></p> - -<p><span class="author-g-by4vjwmiwjiydpj7">Basically, the idea is to trigger JavaScript on some form field event (like <strong>onchange</strong>) to calculate whether the constraint is violated, and then to use the method <code><em>field</em>.setCustomValidity()</code> 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.</span></p> - -<h3 id="Constraint_combining_several_fields_Postal_code_validation">Constraint combining several fields: Postal code validation</h3> - -<p>The postal code format varies from one country to another. Not only do most countries allow an optional prefix with the country code (like <code>D-</code> in Germany, <code>F- </code> 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.</p> - -<div class="note"> -<p><strong>Note: </strong>This is not a comprehensive postal code validation library, but rather a demonstration of the key concepts. </p> -</div> - -<p><span style="line-height: 1.5;">As an example, we will add a script checking the constraint validation for this simple form:</span></p> - -<pre class="brush: 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></pre> - -<p>This displays the following form: </p> - -<p><label>Postal Code: </label><input> <label>Country: </label><select><option value="ch">Switzerland</option><option value="fr">France</option><option value="de">Germany</option><option value="nl">The Netherlands</option></select></p> - -<p>First, we write a function checking the constraint itself:</p> - -<pre class="brush: js">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]); - } -} -</pre> - -<p>Then we link it to the <strong>onchange</strong> event for the {{ HTMLElement("select") }} and the <strong>oninput</strong> event for the {{ HTMLElement("input") }}:</p> - -<pre class="brush: js">window.onload = function () { - document.getElementById("Country").onchange = checkZIP; - document.getElementById("ZIP").oninput = checkZIP; -}</pre> - -<p>You can see a <a href="/@api/deki/files/4744/=constraint.html" title="https://developer.mozilla.org/@api/deki/files/4744/=constraint.html">live example</a> of the postal code validation. </p> - -<h3 id="Limiting_the_size_of_a_file_before_its_upload">Limiting the size of a file before its upload</h3> - -<p>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.</p> - -<p>Here is the HTML part:</p> - -<pre class="brush: html"><label for="FS">Select a file smaller than 75 kB : </label> -<input type="file" id="FS"></pre> - -<p>This displays:</p> - -<p>{{EmbedLiveSample("Limiting_the_size_of_a_file_before_its_upload")}}</p> - -<p>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:</p> - -<pre class="brush: 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"); - return; - } - } - // No custom constraint violation - FS.setCustomValidity(""); -}</pre> - -<p> </p> - -<p>Finally we hook the method with the correct event:</p> - -<pre class="brush: js">window.onload = function () { - document.getElementById("FS").onchange = checkFileSize; -}</pre> - -<p>You can see a <a href="/@api/deki/files/4745/=fileconstraint.html" title="https://developer.mozilla.org/@api/deki/files/4745/=fileconstraint.html">live example</a> of the File size constraint validation.</p> - -<h2 id="Visual_styling_of_constraint_validation"><span class="author-g-by4vjwmiwjiydpj7">Visual styling of constraint validation</span></h2> - -<p>Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled.</p> - -<h3 id="Controlling_the_look_of_elements">Controlling the look of elements</h3> - -<p>The look of elements can be controlled via CSS pseudo-classes.</p> - -<h4 id="required_and_optional_CSS_pseudo-classes">:required and :optional CSS pseudo-classes</h4> - -<p>The <a href="/en-US/docs/Web/CSS/:required" title=":required"><code>:required</code></a> and <a href="/en-US/docs/Web/CSS/:optional" title=":optional"><code>:optional</code></a> <a href="/en-US/docs/Web/CSS/Pseudo-classes" title="Pseudo-classes">pseudo-classes</a> allow writing selectors that match form elements that have the {{ htmlattrxref("required") }} attribute, or that don't have it.</p> - - -<h4 id="-moz-placeholder_CSS_pseudo-class">:-moz-placeholder CSS pseudo-class</h4> - -<p>See <a href="/en-US/docs/Web/CSS/:-moz-placeholder" title="/en-US/docs/Web/CSS/:-moz-placeholder">:-moz-placeholder</a>.</p> - -<h4 id="valid_invalid_CSS_pseudo-classes">:valid :invalid CSS pseudo-classes</h4> - -<p>The <a href="/en-US/docs/Web/CSS/:valid" title="/en-US/docs/Web/CSS/:valid">:valid</a> and <a href="/en-US/docs/Web/CSS/:invalid" title="/en-US/docs/Web/CSS/:invalid?redirectlocale=en-US&redirectslug=CSS%2F%3Ainvalid">:invalid</a> <a href="/en-US/docs/Web/CSS/Pseudo-classes" title="/en-US/docs/Web/CSS/Pseudo-classes?redirectlocale=en-US&redirectslug=CSS%2FPseudo-classes">pseudo-classes</a> 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.</p> - -<h4 id="Default_styles">Default styles</h4> - -<h3 id="Controlling_the_text_of_constraints_violation">Controlling the text of constraints violation</h3> - -<h4 id="The_x-moz-errormessage_attribute">The x-moz-errormessage attribute</h4> - -<p>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.</p> - -<div class="note"> -<p style="margin-left: 40px;">Note: This extension is non-standard.</p> -</div> - -<h4 id="Constraint_API's_element.setCustomValidity()">Constraint API's element.setCustomValidity()</h4> - -<p>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.</p> - -<h4 id="Constraint_API's_ValidityState_object"><span class="author-g-by4vjwmiwjiydpj7">Constraint API's ValidityState object</span></h4> - -<p>The DOM <a href="/en-US/docs/Web/API/ValidityState" title="/en-US/docs/Web/API/ValidityState"><code>ValidityState</code></a> interface represents the <em>validity states</em> 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.</p> - -<h3 id="Examples_of_personalized_styling"><span class="author-g-by4vjwmiwjiydpj7">Examples of personalized styling</span></h3> - -<h3 id="HTML4_fallback"><span class="author-g-by4vjwmiwjiydpj7">HTML4 fallback</span></h3> - -<h4 id="Trivial_fallback"><span class="author-g-by4vjwmiwjiydpj7">Trivial fallback</span></h4> - -<h4 id="JS_fallback"><span class="author-g-by4vjwmiwjiydpj7">JS fallback</span></h4> - -<h2 id="Conclusion"><span class="author-g-by4vjwmiwjiydpj7">Conclusion</span></h2> |