Cette traduction est incomplète. Aidez à traduire cet article depuis l'anglais.
La création des formulaires sur le web a toujours été une tâche complexe. Si le balisage en lui même des formulaires reste simple, vérifier la validité et la cohérence de chaque valeur entrée est relativement difficile, et assurer un retour utilisateur correct peut devenir un casse-tête.
HTML5 a introduit de nouveaux mécanismes pour les formulaires : de nouvelles sémantiques ont été ajoutées à l'élément <input>
et aux contraintes de validation, ceci pour faciliter la tâche de vérification de formulaires, coté client. Les règles basiques et usuelles peuvent être validées sans le besoin de Javascript, via l'ajout de nouveaux attributs ; les règles plus complexes peuvent être vérifiées en utilisant l'API de validation de contraintes HTML5 .
Contraintes basiques et intrinsèques
Avec HTML5, les contraintes sont déclarées de deux façons :
- En choisissant la valeur la plus semantiquement appropriée pour l'attribut
type
de l'élément<input>
, par exemple choisir le type email créée automatiquement une contrainte qui vérifie que la valeur entrée soit une valeur d'email valide. - En attribuant des valeurs aux attributs HTML5 liés à la validation, permettant aux contraintes basiques d'etre décrites d'une façon simple, sans avoir besoin de Javascript.
Types d'input liés à la validation
Les contraintes intrinsèques pour l'attribut type
sont :
Types d'input | Description de la contrainte | Invalidation associée |
---|---|---|
<input type="URL"> |
La valeur doit etre une URL absolue, i.e., répondant à un des cas suivant :
The value must be an absolute URL, i.e., one of: |
violation de contrainte Type mismatch |
<input type="email"> |
La valeur doit suivre la grammaire suivante (en notation ABNF) :
Note : Si l'attribut
multiple est défini, plusieurs adresses e-mail peuvent être saisies, séparées par des virgules. Si l'une d'elles ne répond pas aux contraintes définies ici, la validation de contrainte Type mismatch est déclenchée. |
violation de contrainte Type mismatch |
Notez que la plupart des types d'input n'ont pas de contraintes intrinsèques, par exemple certains sont simplement retirés de la logique de validation de contraintes ou sont pourvu d'un algorithme de nettoyage transformant les valeurs incorrectes en valeurs par défaut acceptables.
Attributs liés à la validation
Les attributs suivants sont utilisés pour décrire des contraintes basiques :
Attribut | Types d'input compatibles | Valeurs possibles | Description de la contrainte | Invalidation associée |
---|---|---|---|---|
pattern |
text, search, url, tel, email, password | A JavaScript regular expression (compiled with the ECMAScript 5 global , ignoreCase , and multiline flags disabled) |
La valeur ne correspond pas au motif | Violation de contrainte Pattern mismatch |
min |
range, number | Un nombre valide | La valeur de l'input doit être plus grande ou égale à la valeur de l'attribut | Violation de contrainte Underflow |
date, month, week | Une date valide | |||
datetime, datetime-local, time | Une date + heure valides | |||
max |
range, number | Un nombre valide | La valeur de l'input doit être plus petite ou égale à la valeur de l'attribut | Violation de contrainte Overflow |
date, month, week | Une date valide | |||
datetime, datetime-local, time | Une date + heure valides | |||
required |
text, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file; also on the <select> and <textarea> elements |
none as it is a Boolean attribute: its presence means true, its absence means false | There must be a value (if set). | Violation de contrainte Missing |
step |
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 | |||
maxlength |
text, search, url, tel, email, password; also on the <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 is done through the Constraint Validation API either on a single form element or at the form level, on the <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
orHTMLTextAreaElement
), 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,:valid
or:invalid
, applies.) - By a call to the checkValidity() function on the
HTMLFormElement
interface, which is called statically validating the constraints. - By submitting the form itself, which is called interactively validating the constraints.
- If the
novalidate
attribute is set on the<form>
element, interactive validation of the constraints doesn't happen. - Calling the send() 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.
Constraint combining several fields: Postal code validation
The postal code format varies from one country to another. Not only do most countries allow an optional prefix with the country code (like D-
in Germany, F-
in France or Switzerland), but some countries have postal codes with only a fixed number of digits; others, like the UK, have more complex structures, allowing letters at some specific positions.
Note: This is not a comprehensive postal code validation library, but rather a demonstration of the key concepts.
As an example, we will add a script checking the constraint validation for this simple form:
<form> <label for="ZIP">ZIP : </label> <input type="text" id="ZIP"> <label for="Country">Country : </label> <select id="Country"> <option value="ch">Switzerland</option> <option value="fr">France</option> <option value="de">Germany</option> <option value="nl">The Nederlands</option> </select> <input type="submit" value="Validate"> </form>
This displays the following form:
First, we write a function checking the constraint itself:
function checkZIP() { // For each country, defines the pattern that the ZIP has to follow var constraints = new Array(); constraints.ch = [ '^(CH-)?\\d{4}$', "Switzerland ZIPs must have exactly 4 digits: e.g. CH-1950 or 1950" ]; constraints.fr = [ '^(F-)?\\d{5}$' , "France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012" ]; constraints.de = [ '^(D-)?\\d{5}$' , "Germany ZIPs 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])$', "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]); } } window.onload = function() { document.getElementById("Country").onchange = checkZIP; document.getElementById("ZIP").onchange = checkZIP; }
Then we link it to the onchange event for the <select>
and the oninput event for the <input>
:
window.onload = function () { document.getElementById("Country").onchange = checkZIP; document.getElementById("ZIP").onchange = checkZIP; }
You can see a live example of the postal code validation.
Limiting the size of a file before its upload
Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint API, and especially the field.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.
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 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
See :-moz-placeholder.
:valid :invalid CSS pseudo-classes
The :valid and :invalid pseudo-classes are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly.
Default styles
Controlling the text of constraints violation
The x-moz-errormessage attribute
The x-moz-errormessage attribute is a Mozilla extension that allows you to specify the error message to display when a field does not successfully validate.
Note: This extension is non-standard.
Constraint API's element.setCustomValidity()
The element.setCustomValidity(error) method is used to set a custom error message to be displayed when a form is submitted. The method works by taking a string parameter error. If error is a non-empty string, the method assumes validation was unsuccessful and displays error as an error message. If error is an empty string, the element is considered validated and resets the error message.
The DOM ValidityState
interface represents the validity states that an element can be in, with respect to constraint validation. Together, they help explain why an element's value fails to validate, if it's not valid.