Formulários em HTML

  • Revision slug: HTML/Forms_in_HTML
  • Revision title: Formulários em HTML
  • Revision id: 293736
  • Criado:
  • Criador: -pedrohenrique-
  • É a revisão atual? Não
  • Comentar

Conteúdo da revisão

{{ gecko_minversion_header("2") }}

Elementos e atributos de formulários em HTML5 proporcionam um grau de marcação semântica maior que HTML4 e remove grande parte da tediosa necessidade mexer com scripts e estilos que era necessária em HTML4. As características dos formulários em HTML5 proporcionam uma melhor experiência para usuários por tornarem formulários mais consistentes entre diferentes sites e dar um feedback imediato ao usuário sobre a entrada de dados. Eles também oferecem essa experiência para usuários que possuem scripts desabilitados em seus navegadores.

Este tópico descreve itens novos ou modificados que são suportados por Gecko/Firefox, versão 4 ou mais recente.

O elemento <input>

O elemento {{ HTMLElement("input") }} tem novos valores para o atributo {{ htmlattrxref("type", "input") }}.

  • search: O elemento representa um campo de entrada de pesquisa. Quebras de linha são automaticamente retiradas do valor de entrada, mas nenhuma outra sintaxe é aplicada.
  • tel: O elemento representa um controle para edição de um número telefônico. Quebras de linha são automaticamente retiradas do valor de entrada, mas nenhuma outra sintaxe é aplicada, porque números telefônicos variam muito dependendo do país em que se encontra. Você pode usar atributos como {{ htmlattrxref("pattern", "input") }} e {{ htmlattrxref("maxlength", "input") }} para restringir valores de entrada.
  • url: O elemento representa um controle para edição de uma URL. Quebreas de linha e espaços em branco à esquerda e direita são automaticamente retirados do valor de entrada.
  • email: O elemento representa um endereço de email. Quebras de linha são automaticamente retiradas do valor de entrada. Um email inválido até pode ser colocado, mas o campo de entrada só aceitará se ele respeitar o formato da ABNF 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str ) onde atext é definido em RFC 5322 section 3.2.3, e ldh-str é definido em RFC 1034 section 3.5.

    Nota: Se o atributo {{ htmlattrxref("multiple", "input") }} for aplicado, multiplos endereços de email podem ser colocador neste elemento {{ HTMLElement("input") }} , como uma lista separada por vírgulas, mas este recurso ainda está sendo implementado no Firefox.

O elemento {{ HTMLElement("input") }} também tem novos atributos:

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

O elemento <form>

O elemento {{ HTMLElement("form") }} possui um novo atributo:

  • {{ htmlattrxref("novalidate", "form") }}: Este atributo previne o formulário de ser validado antes de ser enviado.

O elemento <datalist>

O elemento {{ HTMLElement("datalist") }} representa a lista de elementos {{ HTMLElement("option") }} to suggest when filling an {{ HTMLElement("input") }} field.

Você pode usar o atributo {{ htmlattrxref("list", "input") }} em um elemento {{ HTMLElement("input") }} para ligar um específico campo de entrada com um específico elemento {{ HTMLElement("datalist") }}.

O elemento <output>

The {{ HTMLElement("output") }} element represents the result of a calculation.

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

{{ non-standard_inline() }} Gecko 2.0 (but not necessarily other browser engines) supports defining custom validity constraints and error messages for {{ HTMLElement("output") }} elements, and therefore applies the {{ Cssxref(":invalid") }}, {{ Cssxref(":valid") }}, {{ Cssxref(":-moz-ui-invalid") }}, and {{ Cssxref(":-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").

O atributo placeholder

The {{ htmlattrxref("placeholder", "input") }} attribute on {{ HTMLElement("input") }} and {{ HTMLElement("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.

O atributo autofocus

The {{ htmlattrxref("autofocus", "input") }} 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 {{ HTMLElement("input") }}, {{ HTMLElement("button") }}, {{ HTMLElement("select") }}, and {{ HTMLElement("textarea") }} elements. The exception is that autofocus cannot be applied to an {{ htmlattrxref("autofocus", "input") }} element if the {{ htmlattrxref("type", "input") }} 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 {{ HTMLElement("label") }} element attributes. The control property returns the labeled control, that is, the control that the label is for, which is determined by the {{ htmlattrxref("for", "label") }} 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 input data.

If the title attribute is set on the {{ HTMLElement("input") }} element, that string is displayed in a tooltip when validation fails. If the title is set to the empty string, no tooltip is displayed. If the title attribute isn't set, the standard validation message (as specified by the {{ htmlattrxref("x-moz-errormessage") }} attribute or by calling the setCustomValidity() method) is displayed instead.

Note: Constraint validation is not supported on {{ HTMLElement("button") }} elements in a form; to style a button based on the validity of the associated form, use the {{ cssxref(":-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 {{ htmlattrxref("required", "input") }} attribute on the {{ HTMLElement("input") }}, {{ HTMLElement("select") }}, and {{ HTMLElement("textarea") }} elements indicates that a value must be supplied. (On the {{ HTMLElement("input") }} element, {{ htmlattrxref("required", "input") }} applies only in conjunction with certain values of the {{ htmlattrxref("type", "input") }} attribute.)
  • The {{ htmlattrxref("pattern", "input") }} attribute on the {{ HTMLElement("input") }} element constrains the value to match a specific regular expression.
  • The {{ htmlattrxref("min", "input") }} and {{ htmlattrxref("max", "input") }} attributes of the {{ HTMLElement("input") }} element constrain the minimum and maximum values that can be entered.
  • The {{ htmlattrxref("step", "input") }} attribute of the {{ HTMLElement("input") }} element (when used in combination with the {{ htmlattrxref("min", "input") }} and {{ htmlattrxref("max", "input") }} attributes) constrains the granularity of values that can be entered. A value that does not correspond an allowed value step does not validate.
  • The {{ htmlattrxref("maxlength", "input") }} attribute of the {{ HTMLElement("input") }} and {{ HTMLElement("textarea") }} elements constrains the maximum number of characters (in Unicode code points) that the user can enter.
  • The values url and email for the {{ htmlattrxref("type", "input") }} constrain the value to being a valid URL or e-mail address, respectively.

In addition, you can prevent constraint validation by specifying the {{ htmlattrxref("novalidate", "form") }} attribute on the {{ HTMLElement("form") }}, or the {{ htmlattrxref("formnovalidate", "button") }} attribute on the {{ HTMLElement("button") }} element and on the {{ HTMLElement("input") }} element (when {{ htmlattrxref("type", "input") }} 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.

{{ languages({"es": "es/HTML/HTML5/Formularios_en_HTML5", "ja": "ja/HTML/HTML5/Forms_in_HTML5", "ko": "ko/HTML/HTML에서_폼"}) }}

{{ HTML5ArticleTOC() }}

Fonte da revisão

<p>{{ gecko_minversion_header("2") }}</p>
<p>Elementos e atributos de formulários em <strong>HTML5</strong> proporcionam um grau de marcação semântica maior que HTML4 e remove grande parte da tediosa necessidade mexer com scripts e estilos que era necessária em HTML4. As características dos formulários em HTML5 proporcionam uma melhor experiência para usuários por tornarem formulários mais consistentes entre diferentes sites e dar um feedback imediato ao usuário sobre a entrada de dados. Eles também oferecem essa experiência para usuários que possuem scripts desabilitados em seus navegadores.</p>
<p>Este tópico descreve itens novos ou modificados que são suportados por Gecko/Firefox, versão 4 ou mais recente.</p>
<h3 id="O_elemento_&lt;input&gt;">O elemento <code>&lt;input&gt;</code></h3>
<p>O elemento <code>{{ HTMLElement("input") }}</code> tem novos valores para o atributo {{ htmlattrxref("type", "input") }}.</p>
<ul>
  <li><code>search</code>: O elemento representa um campo de entrada de pesquisa. Quebras de linha são automaticamente retiradas do valor de entrada, mas nenhuma outra sintaxe é aplicada.</li>
  <li><code>tel</code>: O elemento representa um controle para edição de um número telefônico. Quebras de linha são automaticamente retiradas do valor de entrada, mas nenhuma outra sintaxe é aplicada, porque números telefônicos variam muito dependendo do país em que se encontra. Você pode usar atributos como {{ htmlattrxref("pattern", "input") }} e {{ htmlattrxref("maxlength", "input") }} para restringir valores de entrada.</li>
  <li><code>url</code>: O elemento representa um controle para edição de uma <a class="external" href="http://en.wikipedia.org/URL" title="http://en.wikipedia.org/wiki/URL">URL</a>. Quebreas de linha e espaços em branco à esquerda e direita são automaticamente retirados do valor de entrada.</li>
  <li>
    <p><code>email</code>: O elemento representa um endereço de email. Quebras de linha são automaticamente retiradas do valor de entrada. Um email inválido até pode ser colocado, mas o campo de entrada só aceitará se ele respeitar o formato da ABNF <code>1*(&nbsp;atext&nbsp;/&nbsp;"."&nbsp;)&nbsp;"@"&nbsp;ldh-str&nbsp;1*(&nbsp;"."&nbsp;ldh-str&nbsp;)</code> onde <code>atext</code> é definido em <a class="external" href="http://tools.ietf.org/html/rfc5322#section-3.2.3">RFC 5322 section 3.2.3</a>, e <code>ldh-str</code> é definido em <a class="external" href="http://tools.ietf.org/html/rfc1034#section-3.5">RFC 1034 section 3.5</a>.</p>
    <div class="note">
      <strong>Nota:</strong> Se o atributo {{ htmlattrxref("multiple", "input") }} for aplicado, multiplos endereços de email podem ser colocador neste elemento {{ HTMLElement("input") }} , como uma lista separada por vírgulas, mas este recurso ainda está sendo implementado no Firefox.</div>
  </li>
</ul>
<p>O elemento {{ HTMLElement("input") }} também tem novos atributos:</p>
<ul>
  <li>{{ htmlattrxref("list", "input") }}: The ID of a {{ HTMLElement("datalist") }} element whose content, {{ HTMLElement("option") }} elements, are to be used as hints and are displayed as proposals in the suggestion area of the input field.</li>
  <li>{{ htmlattrxref("pattern", "input") }}:&nbsp;A regular expression that the control's value is checked against, which can be used with {{ htmlattrxref("type", "input") }} values of <code>text</code>, <code>tel</code>, <code>search</code>, <code>url</code>, and <code>email</code>.</li>
  <li>{{ htmlattrxref("formmethod", "input") }}: A string indicating which HTTP&nbsp;method (GET or POST) should be used when submitting; it overrides the {{ htmlattrxref("method", "form") }} of the {{ HTMLElement("form") }} element, if defined. The {{ htmlattrxref("formmethod", "input") }} only applies when the&nbsp;{{ htmlattrxref("type", "input") }} is <code>image</code> or <code>submit</code>.</li>
  <li>{{ htmlattrxref("x-moz-errormessage", "input") }} {{ non-standard_inline() }}:&nbsp;A string that is displayed as an error message when the field fails to validate. This is a Mozilla extension, and is non-standard.</li>
</ul>
<h3 id="O_elemento_&lt;form&gt;">O elemento <code>&lt;form&gt;</code></h3>
<p>O elemento {{ HTMLElement("form") }} possui um novo atributo:</p>
<ul>
  <li>{{ htmlattrxref("novalidate", "form") }}: Este atributo previne o formulário de ser validado antes de ser enviado.</li>
</ul>
<h3 id="O_elemento_&lt;datalist&gt;">O elemento <code>&lt;datalist&gt;</code></h3>
<p>O elemento {{ HTMLElement("datalist") }} representa a lista de elementos {{ HTMLElement("option") }} to suggest when filling an {{ HTMLElement("input") }} field.</p>
<p>Você pode usar o atributo {{ htmlattrxref("list", "input") }} em um elemento {{ HTMLElement("input") }} para ligar um específico campo de entrada com um específico elemento {{ HTMLElement("datalist") }}.</p>
<h3 id="O_elemento_&lt;output&gt;">O elemento <code>&lt;output&gt;</code></h3>
<p>The <code>{{ HTMLElement("output") }}</code> element represents the result of a calculation.</p>
<p>You can use the {{ htmlattrxref("for", "output") }} attribute to specify a relationship between the <code>{{ HTMLElement("output") }}</code> element and other elements in the document that affected the calculation (for example, as inputs or parameters). The value of the {{ htmlattrxref("for", "output") }} attribute is a space-separated list of IDs of other elements.</p>
<p>{{ non-standard_inline() }} Gecko 2.0 (but not necessarily other browser engines) supports defining custom validity constraints and error messages for {{ HTMLElement("output") }} elements, and therefore applies the {{ Cssxref(":invalid") }}, {{ Cssxref(":valid") }}, {{ Cssxref(":-moz-ui-invalid") }}, and {{ Cssxref(":-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").</p>
<h3 id="O_atributo_placeholder">O atributo <em>placeholder</em></h3>
<p>The {{ htmlattrxref("placeholder", "input") }} attribute on <code>{{ HTMLElement("input") }}</code> and <code>{{ HTMLElement("textarea") }}</code> 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.</p>
<h3 id="O_atributo_autofocus">O atributo <em>autofocus</em></h3>
<p>The {{ htmlattrxref("autofocus", "input") }} 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 <code>autofocus</code> attribute, which is a Boolean. This attribute can be applied to the <code>{{ HTMLElement("input") }}</code>, <code>{{ HTMLElement("button") }}</code>, <code>{{ HTMLElement("select") }}</code>, and <code>{{ HTMLElement("textarea") }}</code> <!-- and <code>keygen</code> -->elements. The exception is that <code>autofocus</code> cannot be applied to an {{ htmlattrxref("autofocus", "input") }} element if the {{ htmlattrxref("type", "input") }} attribute is set to <code>hidden</code> (that is, you cannot automatically set focus to a hidden control).</p>
<h3 id="The_label.control_DOM.C2.A0property">The label.control DOM&nbsp;property</h3>
<p>The <code><a href="/en/DOM/HTMLLabelElement" title="en/DOM/HTMLLabelElement">HTMLLabelElement</a></code> DOM interface provides an extra property, in addition to the properties that correspond to the HTML <code>{{ HTMLElement("label") }}</code> element attributes. The <strong>control</strong> property returns the labeled control, that is, the control that the label is for, which is determined by the {{ htmlattrxref("for", "label") }} attribute (if it is defined) or by the first descendant control element.</p>
<h3 id="Constraint_Validation">Constraint Validation</h3>
<p>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 input data.</p>
<p>If the <code>title</code> attribute is set on the {{ HTMLElement("input") }}&nbsp;element, that string is displayed in a tooltip when validation fails. If the <code>title</code> is set to the empty string, no tooltip is displayed. If the <code>title</code> attribute isn't set, the standard validation message (as specified by the {{ htmlattrxref("x-moz-errormessage") }} attribute or by calling the <code>setCustomValidity()</code>&nbsp;method) is displayed instead.</p>
<div class="note">
  <strong>Note:</strong> Constraint validation is not supported on {{ HTMLElement("button") }}&nbsp;elements in a form; to style a button based on the validity of the associated form, use the {{ cssxref(":-moz-submit-invalid") }}&nbsp;pseudo-class.</div>
<h4 id="HTML.C2.A0Syntax_for_Constraint_Validation">HTML&nbsp;Syntax for Constraint Validation</h4>
<p>The following items in HTML5 syntax can be used to specify constraints on form data.</p>
<ul>
  <li>The {{ htmlattrxref("required", "input") }} attribute on the {{ HTMLElement("input") }}, {{ HTMLElement("select") }}, and {{ HTMLElement("textarea") }} elements indicates that a value must be supplied. (On the {{ HTMLElement("input") }} element, {{ htmlattrxref("required", "input") }} applies only in conjunction with certain values of the {{ htmlattrxref("type", "input") }} attribute.)</li>
  <li>The {{ htmlattrxref("pattern", "input") }}&nbsp;attribute on the {{ HTMLElement("input") }} element constrains the value to match a specific regular expression.</li>
  <li>The {{ htmlattrxref("min", "input") }} and {{ htmlattrxref("max", "input") }} attributes of the {{ HTMLElement("input") }} element constrain the minimum and maximum values that can be entered.</li>
  <li>The {{ htmlattrxref("step", "input") }} attribute of the {{ HTMLElement("input") }} element (when used in combination with the {{ htmlattrxref("min", "input") }} and {{ htmlattrxref("max", "input") }} attributes) constrains the granularity of values that can be entered. A value that does not correspond an allowed value step does not validate.</li>
  <li>The {{ htmlattrxref("maxlength", "input") }} attribute of the {{ HTMLElement("input") }} and {{ HTMLElement("textarea") }} elements constrains the maximum number of characters (in Unicode code points) that the user can enter.</li>
  <li>The values <code>url</code> and <code>email</code> for the {{ htmlattrxref("type", "input") }} constrain the value to being a valid URL or e-mail address, respectively.</li>
</ul>
<p>In addition, you can prevent constraint validation by specifying the {{ htmlattrxref("novalidate", "form") }} attribute on the {{ HTMLElement("form") }}, or the {{ htmlattrxref("formnovalidate", "button") }} attribute on the {{ HTMLElement("button") }} element and on the {{ HTMLElement("input") }} element (when {{ htmlattrxref("type", "input") }} is <code>submit</code> or <code>image</code>). These attributes indicate that the form is not to be validated when it is submitted.</p>
<h4 id="Constraint_Validation_API">Constraint Validation API</h4>
<p>The following DOM properties and methods related to constraint validation are available to client-side scripts:</p>
<ul>
  <li>On <code><a href="/en/DOM/HTMLFormElement" title="en/DOM/HTMLFormElement">HTMLFormElement</a></code> objects, the <code>checkValidity()</code> 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.</li>
  <li>On <a href="/en/HTML/Content_categories#form-associated" title="en/HTML/Content Categories#form-associated">form-associated elements</a>:
    <ul>
      <li><code>willValidate</code> property, which is false if the element has constraints that are not satisfied.</li>
      <li><code>validity</code> property, which is a <code><a href="/en/DOM/ValidityState" title="en/DOM/ValidityState Interface">ValidityState</a></code> object representing the validity states that the element is in (i.e., constraint failure or success conditions).</li>
      <li><code>validationMessage</code> property, which is a message describing any constraint failures that pertain to the element.</li>
      <li><code>checkValidity()</code>&nbsp;method, which returns false if the element fails to satisfy any of its constraints, or true otherwise.</li>
      <li><code>setCustomValidity()</code> method, which sets a custom validation message, allowing for constraints to be imposed and validated beyond those that are predefined.</li>
    </ul>
  </li>
</ul>
<p>{{ languages({"es": "es/HTML/HTML5/Formularios_en_HTML5", "ja": "ja/HTML/HTML5/Forms_in_HTML5", "ko": "ko/HTML/HTML에서_폼"}) }}</p>
<p>{{ HTML5ArticleTOC() }}</p>
Reverter para esta revisão