Constraint validation

  • Revision slug: HTML/HTML5/Constraint_validation
  • Revision title: Constraint validation
  • Revision id: 71107
  • Created:
  • Creator: teoli
  • Is current revision? No
  • Comment linkification + better wording; 6 words added, 1 words removed

Revision Content

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 even more difficult, and informing the user about the problem may become a headache.

HTML5 introduced new mechanisms for forms: it added new semantic types for the {{ HTMLElement("input") }} element and constraint validation 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 HTML5 Constraint Validation API.

Note: HTML5 Constraint validation doesn't remove the need for validation on the server-side. 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.

Intrinsic and basic constraints

In HTML5, basic constraints are declared in two different ways:

  • By choosing the most semantically appropriate value for the {{ htmlattrxref("type", "input") }} attribute of the {{ HTMLElement("input") }} element. E.g., choosing the email type automatically creates a constraint that checks whether the value is a valid e-mail address.
  • By setting values on validation-related attributes, allowing basic constraints to be described in a simple way, without the need for JavaScript:

Semantic input types

The intrinsic constraints for the {{ htmlattrxref("type", "input") }} attribute are:

Input type Constraint description Associated violation
<input type="URL"> The value must be an absolute URL, i.e., one of:
  • a valid URI (as defined in RFC 3986)
  • a valid IRI, without a query component (as defined in RFC 3987)
  • a valid IRI, with a query component without any unescaped non-ASCII character (as defined in RFC 3987)
  • a valid IRI, and the character set for the document is UTF-8 or UTF-16 (as defined in RFC 3987)
Type mismatch constraint violation
 <input type="email"> The value must follow the ABNF production: 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str ) where:
  • atext is defined in RFC 5322, i.e., a US-ASCII letter (A to Z and a-z), a digit (0 to 9) or one of the following! # $ % & ' * + - / = ? ` { } | ~ special character,
  • ldh-str is defined in RFC 1034, i.e., US-ASCII letters, mixed with digits and - grouped in words separated by a dot (.).
Note: 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 Type mismatch constraint violation is triggered.
Type mismatch constraint violation

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. 

The following attributes are used to describe basic constraints:

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

Constraint validation process

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:

  • By a call to the willValidate() method on a form-related DOM interface (HTMLInputElement, HTMLSelectElement, HTMLButtonElement or HTMLTextAreaElement), 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 CSS pseudo-classes, {{ Cssxref(":valid") }} or {{ Cssxref(":invalid") }}, applies.)
  • By a call to the checkValidity() function on HTMLFormElement interface, which is called statically validating the constraints.
  • By submitting the form itself, which is called interactively validating the constraints.
Note:
  • If the {{ htmlattrxref("novalidate", "form") }} attribute is set on the {{ HTMLElement("form") }} element, interactive validation of the constraints doesn't happen.
  • Calling the form() method on the HTMLFormElement interface doesn't trigger a constraint validation. In other words, this method sends the form data to the server even if doesn't satisfy the constraints.

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; 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; other, like the UK, have more complex structure, allowing letters at some specific positions.

Note: This example doesn't pretend to implement an exhaustive postal code constraint validator and merely is a demonstration on how to implement complex constraint validation using the HTML5 Constraint API.

As an example, we will add a script checking the constraint validation for this simple form:

<label for="PostalCode">Postal Code: </label>
<input type="text&quot;" id="PostalCode"> 
<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>

This displays the following form: 

First, we write a function checking the constraint itself:

function checkPostal() {
  // For each country, defines the pattern that the postal code must follow
  var constraints = new Array();
  constraints.ch = [ '^(CH-)?\\d{4}$', "Postal codes for Switzerland must have exactly 4 digits: e.g. CH-1950 or 1950" ];
  constraints.fr = [ '^(F-)?\\d{5}$' , "Postal codes for France must have exactly 5 digits: e.g. F-75012 or 75012"   ];

  constraints.de = [ '^(D-)?\\d{5}$' , "Postal codes for Germany must have exactly 5 digits: e.g. D-12345 or 12345" ];
  constraints.nl = [ '^(NL-)?\\d{4}\\s*([A-RU-Z][A-Z]|S[BCE-RT-Z])$',
                    "Postal codes for the Netherlands 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 PostalField = document.getElementById("PostalCode");

  // Build the constraint checker
  var constraint = new RegExp(constraints[country][0], "");

  // Check it!
  if (constraint.test(ZIPField.value)) {
    // The postal code follows the constraint, so it doesn't need a validity message. 
    PostalField.setCustomValidity("");
  }
  else {
    // The postal code doesn't follow the constraint, we use the ConstraintAPI to
    // give a message about the format required for this country. 
    PostalField.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 = checkPostal;
  document.getElementById("PostalCode").onchange = checkPostal;
}

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.setCustomValidityUI() 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 > 75000) { // 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. One typical way to use such a selector is to add a '*' after a mandatory field:

*:required:after {
  content: "*";
}

:-moz-placeholder CSS pseudo-class

:valid :invalid CSS pseudo-classes

Default styles<

Controlling the text of constraints violation

The x-moz-errormessage attribute

Constraint API's element.setCustomValidity()

Constraint API's ValidityState object

Examples of personalized styling

HTML4 fallback

Trivial fallback

JS fallback

Conclusion

Revision Source

<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 even more difficult, and informing the user about the problem may become a headache.</p>
<p><a href="/en/HTML/HTML5" title="en/HTML/HTML5">HTML5</a> introduced new mechanisms for forms: it added new semantic types for the {{ HTMLElement("input") }} 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 HTML5 <a href="/en/HTML/HTML5/Forms_in_HTML5#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="Intrinsic_and_basic_constraints">Intrinsic and basic constraints</h2>
<p>In HTML5, basic constraints are declared in two different ways:</p>
<ul> <li>By choosing the most semantically appropriate value for the {{ htmlattrxref("type", "input") }} attribute of the {{ HTMLElement("input") }} element. E.g., choosing the <span style="font-family: Courier New;">email</span> type automatically creates a constraint that checks whether the value is a valid e-mail 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>
<h3 id="Semantic_input_types">Semantic input types</h3>
<p>The intrinsic constraints for the {{ htmlattrxref("type", "input") }} attribute are:</p>
<table class="standard-table"> <thead> <tr> <th scope="col">Input type</th> <th scope="col">Constraint description</th> <th scope="col">Associated violation</th> </tr> </thead> <tbody> <tr> <td><span style="font-family: Courier New;"> &lt;input type="URL"&gt;</span></td> <td>The value must be an absolute URL, i.e., one of: <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;">&lt;input type="email"&gt;</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;">! # $ % &amp; ' * + - / = ? ` { } | ~ </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" title="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="Validation-related_attributes">Validation-related attributes</h3>
<p>The following attributes are used to describe basic constraints:</p>
<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>{{ htmlattrxref("pattern", "input") }}</td> <td>text, search, url, tel, email, password</td> <td>A <a href="/en/JavaScript/Guide/Regular_Expressions" title="https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions">JavaScript regular expression</a> (compiled with 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>The value must match the pattern.</td> <td><strong>Pattern mismatch</strong> constraint violation</td> </tr> <tr> <td rowspan="3">{{ htmlattrxref("min", "input") }} {{ unimplemented_inline() }}</td> <td>range, number</td> <td>A valid number</td> <td rowspan="3">The value must be greater than or equal to the value.</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") }} {{ unimplemented_inline() }}</td> <td>range, number</td> <td>A valid number</td> <td rowspan="3">The value must be less than or equal to the value</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, range, number; 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") }} {{ unimplemented_inline() }}</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 willValidate() method on a form-related <a href="/en/DOM" title="en/DOM">DOM</a> interface (<code><a href="/en/DOM/HTMLInputElement" title="en/DOM/HTMLInputElement">HTMLInputElement</a></code>, <code><a href="/en/DOM/HTMLSelectElement" title="en/DOM/HTMLSelectElement">HTMLSelectElement</a></code>, <code><a href="/en/DOM/HTMLButtonElement" title="en/DOM/HTMLButtonElement">HTMLButtonElement</a></code> or <code><a href="/en/DOM/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/CSS" title="en/CSS">CSS</a> pseudo-classes, {{ Cssxref(":valid") }} or {{ Cssxref(":invalid") }}, applies.)</li> <li>By a call to the checkValidity() function on <code><a href="/en/DOM/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: <br>
</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 form() 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; 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- in France or </code> Switzerland), but some countries have postal codes with only a fixed number of digits; other, like the UK, have more complex structure, allowing letters at some specific positions.</p>
<div class="note"><strong>Note:</strong> This example doesn't pretend to implement an exhaustive postal code constraint validator and merely is a demonstration on how to implement complex constraint validation using the HTML5 Constraint API.</div>
<p>As an example, we will add a script checking the constraint validation for this simple form:</p>
<pre class="code">&lt;label for="PostalCode"&gt;Postal Code: &lt;/label&gt;
&lt;input type="text&amp;quot;" id="PostalCode"&gt; 
&lt;label for="Country"&gt;Country: &lt;/label&gt;
&lt;select id="Country"&gt;
  &lt;option value="ch"&gt;Switzerland&lt;/option&gt;
  &lt;option value="fr"&gt;France&lt;/option&gt;
  &lt;option value="de"&gt;Germany&lt;/option&gt;
  &lt;option value="nl"&gt;The Netherlands&lt;/option&gt;
&lt;/select&gt;</pre>
<p>This displays the following form: </p>
<p><label for="PostalCode">Postal Code: </label><input id="PostalCode" type='text"'> <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></p>
<p>First, we write a function checking the constraint itself:</p>
<pre class="code">function checkPostal() {
  // For each country, defines the pattern that the postal code must follow
  var constraints = new Array();
  constraints.ch = [ '^(CH-)?\\d{4}$', "Postal codes for Switzerland must have exactly 4 digits: e.g. CH-1950 or 1950" ];
  constraints.fr = [ '^(F-)?\\d{5}$' , "Postal codes for France must have exactly 5 digits: e.g. F-75012 or 75012"   ];

  constraints.de = [ '^(D-)?\\d{5}$' , "Postal codes for Germany must have exactly 5 digits: e.g. D-12345 or 12345" ];
  constraints.nl = [ '^(NL-)?\\d{4}\\s*([A-RU-Z][A-Z]|S[BCE-RT-Z])$',
                    "Postal codes for the Netherlands 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 PostalField = document.getElementById("PostalCode");

  // Build the constraint checker
  var constraint = new RegExp(constraints[country][0], "");

  // Check it!
  if (constraint.test(ZIPField.value)) {
    // The postal code follows the constraint, so it doesn't need a validity message. 
    PostalField.setCustomValidity("");
  }
  else {
    // The postal code doesn't follow the constraint, we use the ConstraintAPI to
    // give a message about the format required for this country. 
    PostalField.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="code">window.onload = function () {
  document.getElementById("Country").onchange = checkPostal;
  document.getElementById("PostalCode").onchange = checkPostal;
}
</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.setCustomValidityUI() method, with another JavaScript API, here the HTML5 File API.</p>
<p>Here is the HTML part:</p>
<pre class="code">&lt;label for="FS"&gt;Select a file smaller than 75 kB : &lt;/label&gt;
&lt;input type="file" id="FS"&gt;</pre>
<p>This displays:</p>
<p><label for="FS">Select a file smaller than 75 kB : </label> <input id="FS" type="file"></p>
<p> </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="code">function checkFileSize() {
  var FS = document.getElementById("FS");
  var files = FS.files;

  // If there is (at least) one file selected
  if (files.length &gt; 0) {
     if (files[0].size &gt; 75000) { // 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="code">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/CSS/:required" title=":required"><code>:required</code></a> and <a href="/en/CSS/:optional" title=":optional"><code>:optional</code></a> <a href="/en/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. One typical way to use such a selector is to add a '<code>*</code>' after a mandatory field:</p>
<pre class="code">*:required:after {
  content: "*";
}
</pre>
<h4 id=":-moz-placeholder_CSS_pseudo-class">:-moz-placeholder CSS pseudo-class</h4>
<h4 id=":valid_:invalid_CSS_pseudo-classes">:valid :invalid CSS pseudo-classes</h4>
<h4 id="Default_styles&lt;">Default styles&lt;</h4>
<h3 id="Controlling_the_text_of_constraints_violation
">Controlling the text of constraints violation<span class="author-g-by4vjwmiwjiydpj7"><br>
</span></h3>
<h4 id="The_x-moz-errormessage_attribute">The x-moz-errormessage attribute</h4>
<h4 id="Constraint_API's_element.setCustomValidity()">Constraint API's element.setCustomValidity()</h4>
<h4 id="Constraint_API's_ValidityState_object
"><span class="author-g-by4vjwmiwjiydpj7">Constraint API's ValidityState object<br>
</span></h4>
<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<br>
</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>
Revert to this revision