1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
|
---
title: 约束验证
slug: Web/Guide/HTML/Constraint_validation
translation_of: Web/Guide/HTML/Constraint_validation
tags:
- CSS
- Guide
- HTML5
- NeedsContent
- Selectors
---
<p>创建web表单始终是一个复杂的任务. 仅仅组装表单是容易的,但是检查每一个字段的值是否有效并且一致是一件更加困难的事情,而向用户指明错误可能会令人头痛。<a href="/en-US/docs/Web/Guide/HTML/HTML5" title="en/HTML/HTML5">HTML5</a> 引入了表单相关的一些新的机制:为{{ HTMLElement("input") }}元素和强制校验增加了一些新的语义类型,使得在客户端检查表单内容的工作变得容易。基本上,在填写字段时,通常这些约束都会被检查,而不需要额外的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>Note:</strong> HTML5 Constraint validation doesn't remove the need for validation on the <em>server side</em>. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without JavaScript) or by bad guys trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side.</div>
<h2 id="固有和基本的约束">固有和基本的约束</h2>
<p>在 HTML5中,声明基本的约束有两种方式:</p>
<ul>
<li>给 {{ HTMLElement("input") }} 元素的 {{ htmlattrxref("type", "input") }} 特性选择最合适的语义化的值,比如,选择 email 类型将会自动创建一个约束用于检查输入的值是否是一个有效的 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 类型</th>
<th scope="col">约束描述</th>
<th scope="col">Associated violation</th>
</tr>
</thead>
<tbody>
<tr>
<td><span style="font-family: courier new;"><input type="URL"></span></td>
<td>值必须是绝对的URL, 即,是下面的某一种:
<ul>
<li>a valid URI (as defined in <a class="external" href="http://www.ietf.org/rfc/rfc3986.txt" title="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>)</li>
<li>a valid IRI, without a query component (as defined in <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li>
<li>a valid IRI, with a query component without any unescaped non-ASCII character (as defined in <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li>
<li>a valid IRI, and the character set for the document is UTF-8 or UTF-16 (as defined in <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>The value must follow the <a class="external" href="http://www.ietf.org/rfc/std/std68.txt" title="http://www.ietf.org/rfc/std/std68.txt">ABNF</a> production: <code>1*( atext / "." ) "@" ldh-str 1*( "." ldh-str )</code> where:
<ul>
<li><code>atext</code> is defined in <a class="external" href="http://tools.ietf.org/html/rfc5322" title="http://tools.ietf.org/html/rfc5322">RFC 5322</a>, i.e., a US-ASCII letter (<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>), a digit (<span style="font-family: courier new;">0</span> to <span style="font-family: courier new;">9</span>) or one of the following<span style="font-family: courier new;">! # $ % & ' * + - / = ? ` { } | ~ </span>special character,</li>
<li><code>ldh-str</code> is defined in <a class="external" href="http://www.apps.ietf.org/rfc/rfc1034.html#sec-3.5">RFC 1034</a>, i.e., US-ASCII letters, mixed with digits and <span style="font-family: courier new;">-</span> grouped in words separated by a dot (<span style="font-family: courier new;">.</span>).</li>
</ul>
<div class="note"><strong>Note:</strong> if the {{ htmlattrxref("multiple", "input") }} attribute is set, several e-mail addresses can be set, as a comma-separated list, for this input. If any of these do not satisfy the condition described here, the <strong>Type mismatch </strong>constraint violation is triggered.</div>
</td>
<td><strong>Type mismatch </strong>constraint violation</td>
</tr>
</tbody>
</table>
<p>Note that most input types don't have intrinsic constraints, as some are simply barred from constraint validation or have a sanitization algorithm transforming incorrect values to a correct default. </p>
<h3 id="验证相关的特性(Attribute)">验证相关的特性(Attribute)</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">Associated violation</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ htmlattrxref("pattern", "input") }}</td>
<td>text, search, url, tel, email, password</td>
<td>A <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" title="https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions">JavaScript regular expression</a> (compiled with the <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>, and <code title="">multiline</code> flags <em>disabled)</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>A valid number</td>
<td rowspan="3">输入的值必须大于等于设置的最小值。</td>
<td rowspan="3"><strong>Underflow</strong> constraint violation</td>
</tr>
<tr>
<td>date, month, week</td>
<td>A valid date</td>
</tr>
<tr>
<td>datetime, datetime-local, time</td>
<td>A valid date and time</td>
</tr>
<tr>
<td rowspan="3">{{ htmlattrxref("max", "input") }}</td>
<td>range, number</td>
<td>A valid number</td>
<td rowspan="3">输入的值必须小于等于设置的最大值。</td>
<td rowspan="3"><strong>Overflow</strong> constraint violation</td>
</tr>
<tr>
<td>date, month, week</td>
<td>A valid date</td>
</tr>
<tr>
<td>datetime, datetime-local, time</td>
<td>A valid date and time</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>none</em> as it is a Boolean attribute: its presence means <em>true</em>, its absence means <em>false</em></td>
<td>There must be a value (if set).</td>
<td><strong>Missing</strong> constraint violation</td>
</tr>
<tr>
<td rowspan="5">{{ htmlattrxref("step", "input") }}</td>
<td>date</td>
<td>An integer number of days</td>
<td rowspan="5">Unless the step is set to the <span style="font-family: courier new;">any</span> literal, the value must be <strong>min</strong> + an integral multiple of the step.</td>
<td rowspan="5"><strong>Step mismatch </strong>constraint violation</td>
</tr>
<tr>
<td>month</td>
<td>An integer number of months</td>
</tr>
<tr>
<td>week</td>
<td>An integer number of weeks</td>
</tr>
<tr>
<td>datetime, datetime-local, time</td>
<td>An integer number of seconds</td>
</tr>
<tr>
<td>range, number</td>
<td>An integer</td>
</tr>
<tr>
<td>{{ htmlattrxref("maxlength", "input") }}</td>
<td>text, search, url, tel, email, password; also on the {{ HTMLElement("textarea") }} element</td>
<td>An integer length</td>
<td>The number of characters (code points) must not exceed the value of the attribute.</td>
<td><strong>Too long</strong> constraint violation</td>
</tr>
</tbody>
</table>
<h2 id="Constraint_validation_process"><span class="author-g-by4vjwmiwjiydpj7">Constraint validation process</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 notranslate"><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 notranslate">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 notranslate">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 notranslate"><label for="FS">Select a file smaller than 75 kB : </label>
<input type="file" id="FS"></pre>
<p>This displays:</p>
<p><label>Select a file smaller than 75 kB : </label> <input></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 notranslate">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>Finally we hook the method with the correct event:</p>
<pre class="brush: js notranslate">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_APIs_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_APIs_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>
|