summaryrefslogtreecommitdiff
path: root/devdocs/html/constraint_validation.html
diff options
context:
space:
mode:
authorCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
committerCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
commit754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch)
treef1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/html/constraint_validation.html
new repository
Diffstat (limited to 'devdocs/html/constraint_validation.html')
-rw-r--r--devdocs/html/constraint_validation.html168
1 files changed, 168 insertions, 0 deletions
diff --git a/devdocs/html/constraint_validation.html b/devdocs/html/constraint_validation.html
new file mode 100644
index 00000000..8c4c5c0e
--- /dev/null
+++ b/devdocs/html/constraint_validation.html
@@ -0,0 +1,168 @@
+<header><h1>Constraint validation</h1></header><div class="section-content">
+<p>The creation of web forms has always been a complex task. While marking up the form itself is easy, checking whether each field has a valid and coherent value is more difficult, and informing the user about the problem may become a headache. <a href="https://developer.mozilla.org/en-US/docs/Glossary/HTML5">HTML5</a> introduced new mechanisms for forms: it added new semantic types for the <a href="element/input"><code>&lt;input&gt;</code></a> element and <em>constraint validation</em> to ease the work of checking the form content on the client side. Basic, usual constraints can be checked, without the need for JavaScript, by setting new attributes; more complex constraints can be tested using the Constraint Validation API.</p> <p>For a basic introduction to these concepts, with examples, see the <a href="https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation">Form validation tutorial</a>.</p> <div class="notecard note" id="sect1"> <p><strong>Note:</strong> HTML 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 such as by bad people trying to trick your web application. Therefore, you need to always also validate input constraints on the server side, in a way that is consistent with what is done on the client side.</p> </div>
+</div>
+<h2 id="intrinsic_and_basic_constraints">Intrinsic and basic constraints</h2>
+<div class="section-content">
+<p>In HTML, basic constraints are declared in two ways:</p> <ul> <li>By choosing the most semantically appropriate value for the <a href="element/input#type"><code>type</code></a> attribute of the <a href="element/input"><code>&lt;input&gt;</code></a> element, e.g., choosing the <code>email</code> type automatically creates a constraint that checks whether the value is a valid email address.</li> <li>By setting values on validation-related attributes, allowing basic constraints to be described in a simple way, without the need for JavaScript.</li> </ul>
+</div>
+<h3 id="semantic_input_types">Semantic input types</h3>
+<div class="section-content">
+<p>The intrinsic constraints for the <a href="element/input#type"><code>type</code></a> attribute are:</p> <figure class="table-container"><div class="_table"><table> <thead> <tr> <th>Input type</th> <th>Constraint description</th> <th>Associated violation</th> </tr> </thead> <tbody> <tr> <td><a href="element/input/url"><code>&lt;input type="URL"&gt;</code></a></td> <td>The value must be an absolute <a href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL">URL</a>, as defined in the <a href="https://url.spec.whatwg.org/" target="_blank">URL Living Standard</a>.</td> <td>
+<strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/typeMismatch">TypeMismatch</a></strong> constraint violation</td> </tr> <tr> <td><a href="element/input/email"><code>&lt;input type="email"&gt;</code></a></td> <td>The value must be a syntactically valid email address, which generally has the format <code>username@hostname.tld</code> but can also be local such as <code>username@hostname</code>.</td> <td>
+<strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/typeMismatch">TypeMismatch</a></strong> constraint violation</td> </tr> </tbody> </table></div></figure> <p>For both of these input types, if the <a href="element/input#multiple"><code>multiple</code></a> attribute is set, several values can be set, as a comma-separated list. If any of these do not satisfy the condition described here, the <strong>Type mismatch</strong> constraint violation is triggered.</p> <p>Note that most input types don't have intrinsic constraints, as some are barred from constraint validation or have a sanitization algorithm transforming incorrect values to a correct default.</p>
+</div>
+<h3 id="validation-related_attributes">Validation-related attributes</h3>
+<div class="section-content">
+<p>In addition to the <code>type</code> attribute described above, the following attributes are used to describe basic constraints:</p> <figure class="table-container"><div class="_table"><table class="standard-table"> <thead> <tr> <th scope="col">Attribute</th> <th scope="col">Input types supporting the attribute</th> <th scope="col">Possible values</th> <th scope="col">Constraint description</th> <th scope="col">Associated violation</th> </tr> </thead> <tbody> <tr> <td><code><a href="attributes/pattern">pattern</a></code></td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code> </td> <td> A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions">JavaScript regular expression</a> (compiled with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global"><code>global</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase"><code>ignoreCase</code></a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline"><code>multiline</code></a> flags <em>disabled</em>) </td> <td>The value must match the pattern.</td> <td> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/patternMismatch"><code>patternMismatch</code></a> constraint violation </td> </tr> <tr> <td rowspan="3"><code><a href="attributes/min">min</a></code></td> <td>
+<code>range</code>, <code>number</code>
+</td> <td>A valid number</td> <td rowspan="3">The value must be greater than or equal to the value.</td> <td rowspan="3"> <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeUnderflow">rangeUnderflow</a></code> constraint violation </td> </tr> <tr> <td>
+<code>date</code>, <code>month</code>, <code>week</code>
+</td> <td>A valid date</td> </tr> <tr> <td>
+<code>datetime-local</code>, <code>time</code>
+</td> <td>A valid date and time</td> </tr> <tr> <td rowspan="3"><code><a href="attributes/max">max</a></code></td> <td>
+<code>range</code>, <code>number</code>
+</td> <td>A valid number</td> <td rowspan="3">The value must be less than or equal to the value</td> <td rowspan="3"> <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/rangeOverflow">rangeOverflow</a></code> constraint violation </td> </tr> <tr> <td>
+<code>date</code>, <code>month</code>, <code>week</code>
+</td> <td>A valid date</td> </tr> <tr> <td>
+<code>datetime-local</code>, <code>time</code>
+</td> <td>A valid date and time</td> </tr> <tr> <td><code><a href="attributes/required">required</a></code></td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code>, <code>date</code>, <code>datetime-local</code>, <code>month</code>, <code>week</code>, <code>time</code>, <code>number</code>, <code>checkbox</code>, <code>radio</code>, <code>file</code>; also on the <a href="element/select"><code>&lt;select&gt;</code></a> and <a href="element/textarea"><code>&lt;textarea&gt;</code></a> 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> <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/valueMissing">valueMissing</a></code> constraint violation </td> </tr> <tr> <td rowspan="5"><code><a href="attributes/step">step</a></code></td> <td><code>date</code></td> <td>An integer number of days</td> <td rowspan="5"> Unless the step is set to the <code>any</code> literal, the value must be <strong>min</strong> + an integral multiple of the step. </td> <td rowspan="5"> <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/stepMismatch">stepMismatch</a></code> constraint violation </td> </tr> <tr> <td><code>month</code></td> <td>An integer number of months</td> </tr> <tr> <td><code>week</code></td> <td>An integer number of weeks</td> </tr> <tr> <td>
+<code>datetime-local</code>, <code>time</code>
+</td> <td>An integer number of seconds</td> </tr> <tr> <td>
+<code>range</code>, <code>number</code>
+</td> <td>An integer</td> </tr> <tr> <td><code><a href="attributes/minlength">minlength</a></code></td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code>; also on the <a href="element/textarea"><code>&lt;textarea&gt;</code></a> element </td> <td>An integer length</td> <td> 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 <a href="element/textarea"><code>&lt;textarea&gt;</code></a>. </td> <td> <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooShort">tooShort</a></code> constraint violation </td> </tr> <tr> <td><code><a href="attributes/maxlength">maxlength</a></code></td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code>; also on the <a href="element/textarea"><code>&lt;textarea&gt;</code></a> element </td> <td>An integer length</td> <td> The number of characters (code points) must not exceed the value of the attribute. </td> <td> <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState/tooLong">tooLong</a></code> constraint violation </td> </tr> </tbody> </table></div></figure>
+</div>
+<h2 id="constraint_validation_process">Constraint validation process</h2>
+<div class="section-content">
+<p>Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the <a href="element/form"><code>&lt;form&gt;</code></a> element itself. The constraint validation is done in the following ways:</p> <ul> <li>By a call to the <code>checkValidity()</code> or <code>reportValidity()</code> method of a form-associated DOM interface, (<a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement"><code>HTMLInputElement</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement"><code>HTMLSelectElement</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement"><code>HTMLButtonElement</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement"><code>HTMLOutputElement</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement"><code>HTMLTextAreaElement</code></a>), which evaluates the constraints only on this element, allowing a script to get this information. The <code>checkValidity()</code> 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, <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:valid"><code>:valid</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid"><code>:invalid</code></a>, applies.) In contrast, the <code>reportValidity()</code> method reports any constraint failures to the user.</li> <li>By a call to the <code>checkValidity()</code> or <code>reportValidity()</code> method on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement"><code>HTMLFormElement</code></a> interface.</li> <li>By submitting the form itself.</li> </ul> <p>Calling <code>checkValidity()</code> is called <em>statically</em> validating the constraints, while calling <code>reportValidity()</code> or submitting the form is called <em>interactively</em> validating the constraints.</p> <div class="notecard note" id="sect2"> <p><strong>Note:</strong></p> <ul> <li>If the <a href="element/form#novalidate"><code>novalidate</code></a> attribute is set on the <a href="element/form"><code>&lt;form&gt;</code></a> element, interactive validation of the constraints doesn't happen.</li> <li>Calling the <code>submit()</code> method on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement"><code>HTMLFormElement</code></a> interface doesn't trigger a constraint validation. In other words, this method sends the form data to the server even if it doesn't satisfy the constraints. Call the <code>click()</code> method on a submit button instead.</li> </ul> </div>
+</div>
+<h2 id="complex_constraints_using_the_constraint_validation_api">Complex constraints using the Constraint Validation API</h2>
+<div class="section-content">
+<p>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.</p> <p>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>field.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.</p>
+</div>
+<h3 id="constraint_combining_several_fields_postal_code_validation">Constraint combining several fields: Postal code validation</h3>
+<div class="section-content">
+<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="notecard note" id="sect3"> <p><strong>Note:</strong> This is not a comprehensive postal code validation library, but rather a demonstration of the key concepts.</p> </div> <p>As an example, we will add a script checking the constraint validation for this simple form:</p> <div class="code-example">
+<p class="example-header"><span class="language-name">html</span></p>
+<pre data-signature="1Z3PqJJcwfuiDNIkpe2t3XlWnaJ4l3yHxEy/yJKTzjM=" data-language="html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>form</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>label</span> <span class="token attr-name">for</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>ZIP<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>ZIP : <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>label</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>text<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>ZIP<span class="token punctuation">"</span></span> <span class="token punctuation">/&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>label</span> <span class="token attr-name">for</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Country<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>Country : <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>label</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Country<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>option</span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>ch<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>Switzerland<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>option</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>option</span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>fr<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>France<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>option</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>option</span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>de<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>Germany<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>option</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>option</span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>nl<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>The Netherlands<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>option</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">&gt;</span></span>
+ <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>submit<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Validate<span class="token punctuation">"</span></span> <span class="token punctuation">/&gt;</span></span>
+<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>form</span><span class="token punctuation">&gt;</span></span>
+</pre>
+</div> <p>This displays the following form:</p>
+<div class="code-example" id="sect4">
+
+<iframe class="sample-code-frame" title="Constraint combining several fields Postal code validation sample" id="frame_constraint_combining_several_fields_postal_code_validation" src="https://live.mdnplay.dev/en-US/docs/Web/HTML/Constraint_validation/runner.html?id=constraint_combining_several_fields_postal_code_validation" loading="lazy"></iframe>
+</div> <p>First, we write a function checking the constraint itself:</p> <div class="code-example">
+<p class="example-header"><span class="language-name">js</span></p>
+<pre data-signature="wX5Y0zKv/vE+7Bbp1bBczlH5zhBjR11IG1nLOWIT37I=" data-language="js"><span class="token keyword">function</span> <span class="token function">checkZIP</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
+ <span class="token comment">// For each country, defines the pattern that the ZIP has to follow</span>
+ <span class="token keyword">const</span> constraints <span class="token operator">=</span> <span class="token punctuation">{</span>
+ <span class="token literal-property property">ch</span><span class="token operator">:</span> <span class="token punctuation">[</span>
+ <span class="token string">"^(CH-)?\\d{4}$"</span><span class="token punctuation">,</span>
+ <span class="token string">"Switzerland ZIPs must have exactly 4 digits: e.g. CH-1950 or 1950"</span><span class="token punctuation">,</span>
+ <span class="token punctuation">]</span><span class="token punctuation">,</span>
+ <span class="token literal-property property">fr</span><span class="token operator">:</span> <span class="token punctuation">[</span>
+ <span class="token string">"^(F-)?\\d{5}$"</span><span class="token punctuation">,</span>
+ <span class="token string">"France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012"</span><span class="token punctuation">,</span>
+ <span class="token punctuation">]</span><span class="token punctuation">,</span>
+ <span class="token literal-property property">de</span><span class="token operator">:</span> <span class="token punctuation">[</span>
+ <span class="token string">"^(D-)?\\d{5}$"</span><span class="token punctuation">,</span>
+ <span class="token string">"Germany ZIPs must have exactly 5 digits: e.g. D-12345 or 12345"</span><span class="token punctuation">,</span>
+ <span class="token punctuation">]</span><span class="token punctuation">,</span>
+ <span class="token literal-property property">nl</span><span class="token operator">:</span> <span class="token punctuation">[</span>
+ <span class="token string">"^(NL-)?\\d{4}\\s*([A-RT-Z][A-Z]|S[BCE-RT-Z])$"</span><span class="token punctuation">,</span>
+ <span class="token string">"Netherland ZIPs must have exactly 4 digits, followed by 2 letters except SA, SD and SS"</span><span class="token punctuation">,</span>
+ <span class="token punctuation">]</span><span class="token punctuation">,</span>
+ <span class="token punctuation">}</span><span class="token punctuation">;</span>
+
+ <span class="token comment">// Read the country id</span>
+ <span class="token keyword">const</span> country <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">"Country"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value<span class="token punctuation">;</span>
+
+ <span class="token comment">// Get the NPA field</span>
+ <span class="token keyword">const</span> ZIPField <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">"ZIP"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
+
+ <span class="token comment">// Build the constraint checker</span>
+ <span class="token keyword">const</span> constraint <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RegExp</span><span class="token punctuation">(</span>constraints<span class="token punctuation">[</span>country<span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
+ console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>constraint<span class="token punctuation">)</span><span class="token punctuation">;</span>
+
+ <span class="token comment">// Check it!</span>
+ <span class="token keyword">if</span> <span class="token punctuation">(</span>constraint<span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>ZIPField<span class="token punctuation">.</span>value<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
+ <span class="token comment">// The ZIP follows the constraint, we use the ConstraintAPI to tell it</span>
+ ZIPField<span class="token punctuation">.</span><span class="token function">setCustomValidity</span><span class="token punctuation">(</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
+ <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
+ <span class="token comment">// The ZIP doesn't follow the constraint, we use the ConstraintAPI to</span>
+ <span class="token comment">// give a message about the format required for this country</span>
+ ZIPField<span class="token punctuation">.</span><span class="token function">setCustomValidity</span><span class="token punctuation">(</span>constraints<span class="token punctuation">[</span>country<span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
+ <span class="token punctuation">}</span>
+<span class="token punctuation">}</span>
+</pre>
+</div> <p>Then we link it to the <strong>onchange</strong> event for the <a href="element/select"><code>&lt;select&gt;</code></a> and the <strong>oninput</strong> event for the <a href="element/input"><code>&lt;input&gt;</code></a>:</p> <div class="code-example">
+<p class="example-header"><span class="language-name">js</span></p>
+<pre data-signature="toTme2fP+9t4AcmiDRcPzkcQkyyTjUK4snHedVlF3pA=" data-language="js">window<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
+ document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">"Country"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>onchange <span class="token operator">=</span> checkZIP<span class="token punctuation">;</span>
+ document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">"ZIP"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>oninput <span class="token operator">=</span> checkZIP<span class="token punctuation">;</span>
+<span class="token punctuation">}</span><span class="token punctuation">;</span>
+</pre>
+</div>
+</div>
+<h3 id="limiting_the_size_of_a_file_before_its_upload">Limiting the size of a file before its upload</h3>
+<div class="section-content">
+<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 Validation API, and especially the <code>field.setCustomValidity()</code> method, with another JavaScript API, here the File API.</p> <p>Here is the HTML part:</p> <div class="code-example">
+<p class="example-header"><span class="language-name">html</span></p>
+<pre data-signature="YxAIQxMLdfl/7aP9wniVLc9TRIu7xUlJlp95wOTjWBM=" data-language="html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>label</span> <span class="token attr-name">for</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>FS<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>Select a file smaller than 75 kB : <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>label</span><span class="token punctuation">&gt;</span></span>
+<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>file<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>FS<span class="token punctuation">"</span></span> <span class="token punctuation">/&gt;</span></span>
+</pre>
+</div> <p>This displays:</p>
+<div class="code-example" id="sect5">
+
+<iframe class="sample-code-frame" title="Limiting the size of a file before its upload sample" id="frame_limiting_the_size_of_a_file_before_its_upload" src="https://live.mdnplay.dev/en-US/docs/Web/HTML/Constraint_validation/runner.html?id=limiting_the_size_of_a_file_before_its_upload" loading="lazy"></iframe>
+</div> <p>The JavaScript reads the file selected, uses the <code>File.size()</code> 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> <div class="code-example">
+<p class="example-header"><span class="language-name">js</span></p>
+<pre data-signature="IKhUQ8DNEHp4CHAnxSJWx7DFggxaBasEJQF2xSgiLB8=" data-language="js"><span class="token keyword">function</span> <span class="token function">checkFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
+ <span class="token keyword">const</span> <span class="token constant">FS</span> <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">"FS"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
+ <span class="token keyword">const</span> files <span class="token operator">=</span> <span class="token constant">FS</span><span class="token punctuation">.</span>files<span class="token punctuation">;</span>
+
+ <span class="token comment">// If there is (at least) one file selected</span>
+ <span class="token keyword">if</span> <span class="token punctuation">(</span>files<span class="token punctuation">.</span>length <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
+ <span class="token keyword">if</span> <span class="token punctuation">(</span>files<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>size <span class="token operator">&gt;</span> <span class="token number">75</span> <span class="token operator">*</span> <span class="token number">1024</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
+ <span class="token comment">// Check the constraint</span>
+ <span class="token constant">FS</span><span class="token punctuation">.</span><span class="token function">setCustomValidity</span><span class="token punctuation">(</span><span class="token string">"The selected file must not be larger than 75 kB"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
+ <span class="token keyword">return</span><span class="token punctuation">;</span>
+ <span class="token punctuation">}</span>
+ <span class="token punctuation">}</span>
+ <span class="token comment">// No custom constraint violation</span>
+ <span class="token constant">FS</span><span class="token punctuation">.</span><span class="token function">setCustomValidity</span><span class="token punctuation">(</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
+<span class="token punctuation">}</span>
+</pre>
+</div> <p>Finally, we hook the method with the correct event:</p> <div class="code-example">
+<p class="example-header"><span class="language-name">js</span></p>
+<pre data-signature="JgpbPlMr+KahKRaWbR5fJq8qlwfToa+ohCNsb/u2x24=" data-language="js">window<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
+ document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">"FS"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>onchange <span class="token operator">=</span> checkFileSize<span class="token punctuation">;</span>
+<span class="token punctuation">}</span><span class="token punctuation">;</span>
+</pre>
+</div>
+</div>
+<h2 id="visual_styling_of_constraint_validation">Visual styling of constraint validation</h2>
+<div class="section-content"><p>Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled.</p></div>
+<h3 id="controlling_the_look_of_elements">Controlling the look of elements</h3>
+<div class="section-content">
+<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="https://developer.mozilla.org/en-US/docs/Web/CSS/:required"><code>:required</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:optional"><code>:optional</code></a> <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes">pseudo-classes</a> allow writing selectors that match form elements that have the <a href="element/input#required"><code>required</code></a> attribute, or that don't have it.</p> <h4 id="placeholder-shown_css_pseudo-class">:placeholder-shown CSS pseudo-class</h4> <p>See <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:placeholder-shown"><code>:placeholder-shown</code></a>.</p> <h4 id="valid_invalid_css_pseudo-classes">:valid :invalid CSS pseudo-classes</h4> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:valid"><code>:valid</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid"><code>:invalid</code></a> <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes">pseudo-classes</a> are used to represent &lt;input&gt; 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>
+</div>
+<h3 id="controlling_the_text_of_constraint_violation">Controlling the text of constraint violation</h3>
+<div class="section-content">
+<p>The following items can help with controlling the text of a constraint violation:</p> <ul> <li>The <code>setCustomValidity(message)</code> method on the following elements: <ul> <li>
+<a href="element/fieldset"><code>&lt;fieldset&gt;</code></a>. Note: Setting a custom validity message on fieldset elements will not prevent form submission in most browsers.</li> <li><a href="element/input"><code>&lt;input&gt;</code></a></li> <li><a href="element/output"><code>&lt;output&gt;</code></a></li> <li><a href="element/select"><code>&lt;select&gt;</code></a></li> <li>Submit buttons (created with either a <a href="element/button"><code>&lt;button&gt;</code></a> element with the <code>submit</code> type, or an <code>input</code> element with the <a href="element/input/submit">submit</a> type. Other types of buttons do not participate in constraint validation.</li> <li><a href="element/textarea"><code>&lt;textarea&gt;</code></a></li> </ul> </li> <li>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/ValidityState"><code>ValidityState</code></a> interface describes the object returned by the <code>validity</code> 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.</li> </ul>
+</div><div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2005&ndash;2023 MDN contributors.<br>Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.<br>
+ <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation" class="_attribution-link">https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation</a>
+ </p>
+</div>