Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Les formulaires en HTML

Cette traduction est incomplète. Aidez à traduire cet article depuis l'anglais.

Les éléments et les attributs des formulaires HTML5 permettent un meilleur balisage sémantique que HTML4 tout en réduisant les besoins de scriptage et l'application de styles qui étaient nécessaires avec HTML4. The forms features in HTML5 provide a better experience for users by making forms more consistent across different web sites and giving immediate feedback to the user about data entry. They also provide this experience to users who have scripting disabled in their browser.

Cet article résume les changements apportés aux formulaires avec HTML5. Pour un guide d'utilisation des formulaires html, consultez notre HTML forms guide.

The <input> element

L'élément <input> possède de nouvelles valeurs pour l'attribut type. (Voir la page de référence de <input> pour une liste complète des attributs, valeurs, et utilisations de cet élément.)

  • search: L'élément représente un champ de saisie de recherche. Les sauts de ligne sont automatiquement rétirés de la valeur de l'input, mais aucune autre syntaxe n'est imposée.
  • tel: L'élément représente un contrôle pour la saisie d'un numéro de téléphone. Les sauts de ligne sont automatiquement rétirés de la valeur de l'input, mais aucune autre syntaxe n'est imposée, car les numéros de téléphone varient considérablement à l'échelle internationale. Vous pouvez utiliser des attributs comme pattern et maxlength pour restreindre les valeurs entrées dans le contrôle.
  • url: L'élément représente un contrôle pour la saisie d'une URL. Les sauts de ligne et les espaces vides de début et de fin sont automatiquement rétirés de la valeur de l'input.
  • email: L'élément représente une adresse email. Les sauts de ligne sont automatiquement rétirés de la valeur de l'input. Une adresse email invalide peut être saisie, mais le champ satisfera ses restrictions propres seulement si l'adresse email satisfait la production ABNF 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str )atext est défini dans la RFC 5322 section 3.2.3, et ldh-str est défini dans la RFC 1034 section 3.5.

    Note: Si l'attribut multiple est défini, plusieurs adresses email peuvent être saisies dans ce champ <input>, sous la forme d'une suite d'éléments séparés par des virgules, mais ceci n'est pour l'instant pas implémenté dans Firefox..

The <input> element also has new attributes:

  • list: The ID of a <datalist> element whose content, <option> elements, are to be used as hints and are displayed as proposals in the suggestion area of the input field.
  • pattern: A regular expression that the control's value is checked against, which can be used with type values of text, tel, search, url, and email.
  • form: A string indicating which <form> element this input is part of. An input can only be in one form.
  • formmethod: A string indicating which HTTP method (GET or POST) should be used when submitting; it overrides the method of the <form> element, if defined. The formmethod only applies when the type is image or submit, and the form attribute has been set.
  • x-moz-errormessage : A string that is displayed as an error message when the field fails to validate. This is a Mozilla extension, and is non-standard.

text input

 

This segment defines a one line input  the user can enter into the box.

<form>
  Enter your Name <input type="text" name="name">
</form>

checkboxes

This section allows the user to select multiple options to choose from a limited numbers of options.

<input type="checkbox" name="chk" value="" checked> Do you want the newsletter

Radio < input> element

<form>
  <input type="radio" name="sex" value="male">Male<br>
  <input type="radio" name="sex" value="female">Female<br>
  <input type="radio" name="sex" value="other">Other
</form>

The <form> element

The <form> element has a new attribute:

  • novalidate: This attribute prevents the form from being validated before its submission.

The <datalist> element

The <datalist> element represents the list of <option> elements to suggest when filling an <input> field.

You can use the list attribute on an <input> element to link a specific input field with a specific <datalist> element.

The <output> element

The <output> element represents the result of a calculation.

You can use the for attribute to specify a relationship between the <output> element and other elements in the document that affected the calculation (for example, as inputs or parameters). The value of the for attribute is a space-separated list of IDs of other elements.

Gecko 2.0 (but not necessarily other browser engines) supports defining custom validity constraints and error messages for <output> elements, and therefore applies the :invalid, :valid, :-moz-ui-invalid, and :-moz-ui-valid CSS pseudo-classes to them. This can be helpful in situations where the calculated result violates a business rule, but no specific input value does (for example, "The total of percentages must not exceed 100").

The placeholder attribute

The placeholder attribute on <input> and <textarea> elements provides a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds.

The autofocus attribute

The autofocus attribute lets you specify that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form item in a document can have the autofocus attribute, which is a Boolean. This attribute can be applied to the <input>, <button>, <select>, and <textarea> elements. The exception is that autofocus cannot be applied to an autofocus element if the type attribute is set to hidden (that is, you cannot automatically set focus to a hidden control).

The label.control DOM property

The HTMLLabelElement DOM interface provides an extra property, in addition to the properties that correspond to the HTML <label> element attributes. The control property returns the labeled control, that is, the control that the label is for, which is determined by the for attribute (if it is defined) or by the first descendant control element.

Constraint Validation

HTML5 provides syntax and API items to support client-side validation of forms. While this functionality does not replace server-side validation, which is still necessary for security and data integrity, client-side validation can support a better user experience by giving the user immediate feedback about the input data.

If the title attribute is set on the <input> element, its value is used as tooltip. However, if the validation fail, this tooltip text will be replaced with the associate error message. It's possible to customize that error message using the non-standard x-moz-errormessage attribute or when calling the setCustomValidity() method.

<input type="email" title="Please, provide an e-mail" x-moz-errormessage="This is not a valid e-mail">
Note: Constraint validation is not supported on <button> elements in a form; to style a button based on the validity of the associated form, use the :-moz-submit-invalid pseudo-class.

HTML Syntax for Constraint Validation

The following items in HTML5 syntax can be used to specify constraints on form data.

  • The required attribute on the <input>, <select>, and <textarea> elements indicates that a value must be supplied. (On the <input> element, required applies only in conjunction with certain values of the type attribute.)
  • The pattern attribute on the <input> element constrains the value to match a specific regular expression.
  • The min and max attributes of the <input> element constrain the minimum and maximum values that can be entered.
  • The step attribute of the <input> element (when used in combination with the min and max attributes) constrains the granularity of values that can be entered. A value that does not correspond an allowed value step does not validate.
  • The maxlength attribute of the <input> and <textarea> elements constrains the maximum number of characters (in Unicode code points) that the user can enter.
  • The values url and email for the type constrain the value to being a valid URL or e-mail address, respectively.

In addition, you can prevent constraint validation by specifying the novalidate attribute on the <form>, or the formnovalidate attribute on the <button> element and on the <input> element (when type is submit or image). These attributes indicate that the form is not to be validated when it is submitted.

Constraint Validation API

The following DOM properties and methods related to constraint validation are available to client-side scripts:

  • On HTMLFormElement objects, the checkValidity() method, which returns true if all of this form element's associated elements that are subject to constraint validation satisfy their constraints, and false if any do not.
  • On form-associated elements:
    • willValidate property, which is false if the element has constraints that are not satisfied.
    • validity property, which is a ValidityState object representing the validity states that the element is in (i.e., constraint failure or success conditions).
    • validationMessage property, which is a message describing any constraint failures that pertain to the element.
    • checkValidity() method, which returns false if the element fails to satisfy any of its constraints, or true otherwise.
    • setCustomValidity() method, which sets a custom validation message, allowing for constraints to be imposed and validated beyond those that are predefined.

See also

Étiquettes et contributeurs liés au document

 Contributeurs à cette page : idealtitude, simon13
 Dernière mise à jour par : idealtitude,