diff options
author | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:49:58 +0100 |
---|---|---|
committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:49:58 +0100 |
commit | 68fc8e96a9629e73469ed457abd955e548ec670c (patch) | |
tree | 8529ab9fe63d011f23c7f22ab5a4a1c5563fcaa4 /files/pt-br/learn/forms | |
parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
download | translated-content-68fc8e96a9629e73469ed457abd955e548ec670c.tar.gz translated-content-68fc8e96a9629e73469ed457abd955e548ec670c.tar.bz2 translated-content-68fc8e96a9629e73469ed457abd955e548ec670c.zip |
unslug pt-br: move
Diffstat (limited to 'files/pt-br/learn/forms')
7 files changed, 3204 insertions, 0 deletions
diff --git a/files/pt-br/learn/forms/basic_native_form_controls/index.html b/files/pt-br/learn/forms/basic_native_form_controls/index.html new file mode 100644 index 0000000000..ebefe55869 --- /dev/null +++ b/files/pt-br/learn/forms/basic_native_form_controls/index.html @@ -0,0 +1,701 @@ +--- +title: Os widgets nativos +slug: Web/Guide/HTML/Forms/Os_widgets_nativos +tags: + - Aprender + - Contrôles + - Exemplos + - Guía + - HTML + - Iniciantes + - Intermediário + - Web +translation_of: Learn/Forms/Basic_native_form_controls +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/HTML/Forms/How_to_structure_an_HTML_form", "Learn/HTML/Forms/Sending_and_retrieving_form_data", "Learn/HTML/Forms")}}</div> + +<p class="summary">Veremos agora, detalhadamente, a funcionalidade dos diferentes widgets dos formulários, observando as opções disponíveis para coletar diferentes tipos de dados. Este guia é um tanto exaustivo, cobrindo todos os widgets de formulários nativos disponíveis.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Pré-requisitos:</th> + <td>Alfabetização básica em informática e um <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">entendimento básico de HTML.</a></td> + </tr> + <tr> + <th scope="row">Objetivo:</th> + <td>Entender quais são os widgets nativos de formulário disponiveis nos navegadores para coletar dados, e como implementa-los usando HTML.</td> + </tr> + </tbody> +</table> + +<p><span class="tlid-translation translation" lang="pt"><span title="">Aqui vamos nos concentrar nos widgets de formulário baseados em navegador, mas como os formulários HTML são muito limitados e a qualidade da implementação pode ser muito diferente de navegador para navegador, os desenvolvedores da Web às vezes criam seus próprios widgets de formulários </span></span>— Veja <a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets">How to build custom form widgets</a> <span class="tlid-translation translation" lang="pt"><span title="">posteriormente neste mesmo módulo para obter mais idéias sobre isso.</span></span></p> + +<div class="note"> +<p><strong>Nota</strong>: A maioria dos recursos discutidos neste artigo possui <span class="tlid-translation translation" lang="pt"><span title="">amplo suporte nos navegadores</span></span>; destacaremos as exceções existentes. Se você quiser mais detalhes, consulte nosso artigo <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element#Forms">referência aos elementos de formulário HTML</a>, <span class="tlid-translation translation" lang="pt"><span title="">e, em particular, nossa extensa referência de </span></span><a href="/en-US/docs/Web/HTML/Element/input">tipos <input></a>.</p> +</div> + +<h2 id="Atributos_comuns">Atributos comuns</h2> + +<p><span class="tlid-translation translation" lang="pt"><span title="">Muitos dos elementos usados para definir widgets de formulário têm seus próprios atributos</span></span>. Entretanto, <span class="tlid-translation translation" lang="pt"><span title="">há um conjunto de atributos comuns a todos os elementos do formulário</span></span>, os quais permitem certo controle sobre os widgets. <span class="tlid-translation translation" lang="pt"><span title="">Aqui está uma lista desses atributos comuns</span></span>:</p> + +<table> + <thead> + <tr> + <th scope="col">Nome do atributo</th> + <th scope="col">Valor padrão</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>autofocus</code></td> + <td>(falso)</td> + <td>Este é um atributo booleano que permite especificar automaticamente qual elemento deverá ter o foco quando a página carregar, a menos que o usuário a substitua, por exemplo <span class="tlid-translation translation" lang="pt"><span title=""> digitando sobre um controle diferente</span></span>. <span class="tlid-translation translation" lang="pt"><span title="">Somente um elemento associado ao formulário em um documento pode ter esse atributo especificado</span></span>.</td> + </tr> + <tr> + <td><code>disabled</code></td> + <td>(<em>falso</em>)</td> + <td>Este é um atributo booleano que indica <span class="tlid-translation translation" lang="pt"><span title="">que o usuário não pode interagir com este elemento</span></span>. Se este atributo não estiver especificado, o elemento, então, herda a configuração do elemento que o contém, por exemplo, {{HTMLElement("fieldset")}}; se o elemento que o contém não possuir o atributo <code>disabled</code>, então o elemento é ativado.</td> + </tr> + <tr> + <td><code>form</code></td> + <td></td> + <td><span class="tlid-translation translation" lang="pt"><span title="">O elemento do formulário ao qual o widget está associado</span></span>. O valor do atributo deve ser o atributo <code>id</code> de um {{HTMLElement("form")}} no mesmo documento. <span class="tlid-translation translation" lang="pt"><span title="">Em teoria, permite colocar um widget fora de um elemento</span></span> {{HTMLElement("form")}}. <span class="tlid-translation translation" lang="pt"><span title="">Na prática, no entanto, não há navegador que suporte esse recurso.</span></span></td> + </tr> + <tr> + <td><code>name</code></td> + <td></td> + <td><span class="tlid-translation translation" lang="pt"><span title="">O nome do elemento. Este atributo é</span><span title=""> enviado com os dados do formulário.</span></span></td> + </tr> + <tr> + <td><code>value</code></td> + <td></td> + <td>O Valor inicial do elemento.</td> + </tr> + </tbody> +</table> + +<h2 id="Text_input_fields">Text input fields</h2> + +<p>Text {{htmlelement("input")}} fields are the most basic form widgets. They are a very convenient way to let the user enter any kind of data. However, some text fields can be specialized to achieve particular needs. We've already seen a few simple examples</p> + +<div class="note"> +<p><strong>Note</strong>: HTML form text fields are simple plain text input controls. This means that you cannot use them to perform <a href="/en-US/docs/Rich-Text_Editing_in_Mozilla" title="/en-US/docs/Rich-Text_Editing_in_Mozilla">rich editing</a> (bold, italic, etc.). All rich text editors you'll encounter out there are custom widgets created with HTML, CSS, and JavaScript.</p> +</div> + +<p>All text fields share some common behaviors:</p> + +<ul> + <li>They can be marked as {{htmlattrxref("readonly","input")}} (the user cannot modify the input value) or even {{htmlattrxref("disabled","input")}} (the input value is never sent with the rest of the form data).</li> + <li>They can have a {{htmlattrxref("placeholder","input")}}; this is text that appears inside the text input box that describes the purpose of the box briefly.</li> + <li>They can be constrained in {{htmlattrxref("size","input")}} (the physical size of the box) and <a href="/en-US/docs/HTML/Element/input#attr-maxlength" title="/en-US/docs/HTML/Element/input#attr-maxlength">length</a> (the maximum number of characters that can be entered into the box).</li> + <li>They can benefit from <a href="/en-US/docs/HTML/Element/input#attr-spellcheck" title="/en-US/docs/HTML/Element/input#attr-spellcheck">spell checking</a>, if the browser supports it.</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: The {{htmlelement("input")}} element is special because it can be almost anything. By simply setting its <code>type</code> attribute, it can change radically, and it is used for creating most types of form widget including single line text fields, controls without text input, time and date controls, and buttons. However, there are some exceptions, like {{htmlelement("textarea")}} for multi-line inputs. Take careful note of these as you read the article.</p> +</div> + +<h3 id="Single_line_text_fields">Single line text fields</h3> + +<p>A single line text field is created using an {{HTMLElement("input")}} element whose {{htmlattrxref("type","input")}} attribute value is set to <code>text</code> (also, if you don't provide the {{htmlattrxref("type","input")}} attribute, <code>text</code> is the default value). The value <code>text</code> for this attribute is also the fallback value if the value you specify for the {{htmlattrxref("type","input")}} attribute is unknown by the browser (for example if you specify <code>type="date"</code> and the browser doesn't support native date pickers).</p> + +<div class="note"> +<p><strong>Note</strong>: You can find examples of all the single line text field types on GitHub at <a href="https://github.com/mdn/learning-area/blob/master/html/forms/native-form-widgets/single-line-text-fields.html">single-line-text-fields.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/native-form-widgets/single-line-text-fields.html">see it live also</a>).</p> +</div> + +<p>Here is a basic single line text field example:</p> + +<pre class="brush: html"><input type="text" id="comment" name="comment" value="I'm a text field"></pre> + +<p>Single line text fields have only one true constraint: if you type text with line breaks, the browser removes those line breaks before sending the data.</p> + +<p><img alt="Screenshots of single line text fields on several platforms." src="/files/4273/all-single-line-text-field.png" style="height: 235px; width: 655px;"></p> + +<p>HTML5 enhances the basic single line text field by adding special values for the {{htmlattrxref("type","input")}} attribute. Those values still turn an {{HTMLElement("input")}} element into a single line text field but they add a few extra constraints and features to the field.</p> + +<h4 id="E-mail_address_field">E-mail address field</h4> + +<p>This type of field is set with the value <code>email</code> for the {{htmlattrxref("type","input")}} attribute:</p> + +<pre class="brush: html"><input type="email" id="email" name="email" multiple></pre> + +<p>When this <code>type</code> is used, the user is required to type a valid e-mail address into the field; any other content causes the browser to display an error when the form is submitted. Note that this is client-side error validation, performed by the browser:</p> + +<p><img alt="An invalid email input showing the message Please enter an email address." src="https://mdn.mozillademos.org/files/14781/email-invalid.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p> + +<p>It's also possible to let the user type several e-mail addresses into the same input (separated by commas) by including the {{htmlattrxref("multiple","input")}} attribute.</p> + +<p>On some devices (especially on mobile), a different virtual keypad might be presented that is more suitable for entering email addresses.</p> + +<div class="note"> +<p><strong>Note</strong>: You can find out more about form validation in the article <a href="/en-US/docs/Learn/HTML/Forms/Form_validation">Form data validation</a>.</p> +</div> + +<h4 id="Password_field">Password field</h4> + +<p>This type of field is set using the value <code>password</code> for the {{htmlattrxref("type","input")}} attribute:</p> + +<pre class="brush: html"><input type="password" id="pwd" name="pwd"></pre> + +<p>It doesn't add any special constraints to the entered text, but it does obscure the value entered into the field (e.g. with dots or asterisks) so it can't be read by others.</p> + +<p>Keep in mind this is just a user interface feature; unless you submit your form securely, it will get sent in plain text, which is bad for security — a malicious party could intercept your data and steal passwords, credit card details, or whatever else you've submitted. The best way to protect users from this is to host any pages involving forms over a secure connection (i.e. at an https:// ... address), so the data is encrypted before it is sent.</p> + +<p>Modern browsers recognize the security implications of sending form data over an insecure connection, and have implemented warnings to deter users from using insecure forms. For more information on what Firefox implements, see <a href="/en-US/docs/Web/Security/Insecure_passwords">Insecure passwords</a>.</p> + +<h4 id="Search_field">Search field</h4> + +<p>This type of field is set by using the value <code>search</code> for the {{htmlattrxref("type","input")}} attribute:</p> + +<pre class="brush: html"><input type="search" id="search" name="search"></pre> + +<p>The main difference between a text field and a search field is how the browser styles it — often, search fields are rendered with rounded corners, and/or given an "x" to press to clear the entered value. However, there is another added feature worth noting: their values can be automatically saved to be auto completed across multiple pages on the same site.</p> + +<p><img alt="Screenshots of search fields on several platforms." src="/files/4269/all-search-field.png" style="height: 235px; width: 655px;"></p> + +<h4 id="Phone_number_field">Phone number field</h4> + +<p>This type of field is set using <code>tel</code> as the value of the {{htmlattrxref("type","input")}} attribute:</p> + +<pre class="brush: html"><input type="tel" id="tel" name="tel"></pre> + +<p>Due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user (this can include letters, etc.). This is primarily a semantic difference, although on some devices (especially on mobile), a different virtual keypad might be presented that is more suitable for entering phone numbers.</p> + +<h4 id="URL_field">URL field</h4> + +<p>This type of field is set using the value <code>url</code> for the {{htmlattrxref("type","input")}} attribute:</p> + +<pre class="brush: html"><input type="url" id="url" name="url"></pre> + +<p>It adds special validation constraints to the field, with the browser reporting an error if invalid URLs are entered.</p> + +<div class="note"><strong>Note:</strong> Just because the URL is well-formed doesn't necessarily mean that it refers to a location that actually exists.</div> + +<div class="note"> +<p><strong>Note</strong>: Fields that have special constraints and are in error prevent the form from being sent; in addition, they can be styled so as to make the error clear. We will discuss this in detail in the article: <a href="/en-US/docs/HTML/Forms/Data_form_validation" title="/en-US/docs/HTML/Forms/Data_form_validation">Data form validation</a>.</p> +</div> + +<h3 id="Multi-line_text_fields">Multi-line text fields</h3> + +<p>A multi-line text field is specified using a {{HTMLElement("textarea")}} element, rather than using the {{HTMLElement("input")}} element.</p> + +<pre class="brush: html"><textarea cols="30" rows="10"></textarea></pre> + +<p>The main difference between a textarea and a regular single line text field is that users are allowed to type text that includes hard line breaks (i.e. pressing return).</p> + +<p><img alt="Screenshots of multi-lines text fields on several platforms." src="/files/4271/all-multi-lines-text-field.png" style="height: 330px; width: 745px;"></p> + +<div class="note"> +<p><strong>Note</strong>: You can find an example of a multi-line text field on GitHub at <a href="https://github.com/mdn/learning-area/blob/master/html/forms/native-form-widgets/multi-line-text-field.html">multi-line-text-field.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/native-form-widgets/multi-line-text-field.html">see it live also</a>). Have a look at it, and notice how in most browsers, the text area is given a drag handle on the bottom right to allow the user to resize it. This resizing ability can be turned off by setting the text area's {{cssxref("resize")}} property to <code>none</code> using <a href="/en-US/docs/Learn/CSS">CSS</a>.</p> +</div> + +<p>{{htmlelement("textarea")}} also accepts a few extra attributes to control its rendering across several lines (in addition to several others):</p> + +<table> + <caption>Attributes for the {{HTMLElement("textarea")}} element</caption> + <thead> + <tr> + <th scope="col">Attribute name</th> + <th scope="col">Default value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{htmlattrxref("cols","textarea")}}</td> + <td><code>20</code></td> + <td>The visible width of the text control, in average character widths.</td> + </tr> + <tr> + <td>{{htmlattrxref("rows","textarea")}}</td> + <td></td> + <td>The number of visible text lines for the control.</td> + </tr> + <tr> + <td>{{htmlattrxref("wrap","textarea")}}</td> + <td><code>soft</code></td> + <td>Indicates how the control wraps text. Possible values are: <code>hard</code> or <code>soft</code></td> + </tr> + </tbody> +</table> + +<p>Note that the {{HTMLElement("textarea")}} element is written a bit differently from the {{HTMLElement("input")}} element. The {{HTMLElement("input")}} element is an empty element, which means that it cannot contain any child elements. On the other hand, the {{HTMLElement("textarea")}} element is a regular element that can contain text content children.</p> + +<p>There are two key related points to note here:</p> + +<ul> + <li>If you want to define a default value for an {{HTMLElement("input")}} element, you have to use the <code>value</code> attribute; for a {{HTMLElement("textarea")}} element on the other hand you put the default text between the starting tag and the closing tag of the {{HTMLElement("textarea")}}.</li> + <li>Because of its nature, the {{HTMLElement("textarea")}} element only accepts text content; this means that any HTML content put inside a {{HTMLElement("textarea")}} is rendered as if it was plain text content.</li> +</ul> + +<h2 id="Drop-down_content">Drop-down content</h2> + +<p>Drop-down widgets are a simple way to let users select one of many options without taking up much space in the user interface. HTML has two forms of drop down content: the <strong>select box</strong>, and <strong>autocomplete box</strong>. In both cases the interaction is the same — once the control is activated, the browser displays a list of values the user can select between.</p> + +<div class="note"> +<p>Note: You can find examples of all the drop-down box types on GitHub at <a href="https://github.com/mdn/learning-area/blob/master/html/forms/native-form-widgets/drop-down-content.html">drop-down-content.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/native-form-widgets/drop-down-content.html">see it live also</a>).</p> +</div> + +<h3 id="Select_box">Select box</h3> + +<p>A select box is created with a {{HTMLElement("select")}} element with one or more {{HTMLElement("option")}} elements as its children, each of which specifies one of its possible values.</p> + +<pre class="brush: html"><select id="simple" name="simple"> + <option>Banana</option> + <option>Cherry</option> + <option>Lemon</option> +</select></pre> + +<p>If required, the default value for the select box can be set using the {{htmlattrxref("selected","option")}} attribute on the desired {{HTMLElement("option")}} element — this option is then preselected when the page loads. The {{HTMLElement("option")}} elements can also be nested inside {{HTMLElement("optgroup")}} elements to create visually associated groups of values:</p> + +<pre class="brush: html"><select id="groups" name="groups"> + <optgroup label="fruits"> + <option>Banana</option> + <option selected>Cherry</option> + <option>Lemon</option> + </optgroup> + <optgroup label="vegetables"> + <option>Carrot</option> + <option>Eggplant</option> + <option>Potato</option> + </optgroup> +</select></pre> + +<p><img alt="Screenshots of single line select box on several platforms." src="/files/4517/all-select.png" style="height: 636px; width: 887px;"></p> + +<p>If an {{HTMLElement("option")}} element is set with a <code>value</code> attribute, that attribute's value is sent when the form is submitted. If the <code>value</code> attribute is omitted, the content of the {{HTMLElement("option")}} element is used as the select box's value.</p> + +<p>On the {{HTMLElement("optgroup")}} element, the <code>label</code> attribute is displayed before the values, but even if it looks somewhat like an option, it is not selectable.</p> + +<h3 id="Multiple_choice_select_box">Multiple choice select box</h3> + +<p>By default, a select box only lets the user select a single value. By adding the {{htmlattrxref("multiple","select")}} attribute to the {{HTMLElement("select")}} element, you can allow users to select several values, by using the default mechanism provided by the operating system (e.g. holding down <kbd>Cmd</kbd>/<kbd>Ctrl</kbd> and clicking multiple values).</p> + +<p>Note: In the case of multiple choice select boxes, the select box no longer displays the values as drop-down content — instead, they are all displayed at once in a list.</p> + +<pre class="brush: html"><select multiple id="multi" name="multi"> + <option>Banana</option> + <option>Cherry</option> + <option>Lemon</option> +</select></pre> + +<p><img alt="Screenshots of multi-lines select box on several platforms." src="/files/4559/all-multi-lines-select.png" style="height: 531px; width: 734px;"></p> + +<div class="note"><strong>Note:</strong> All browsers that support the {{HTMLElement("select")}} element also support the {{htmlattrxref("multiple","select")}} attribute on it.</div> + +<h3 id="Autocomplete_box">Autocomplete box</h3> + +<p>You can provide suggested, automatically-completed values for form widgets using the {{HTMLElement("datalist")}} element with some child {{HTMLElement("option")}} elements to specify the values to display.</p> + +<p>The data list is then bound to a text field (usually an <code><input></code> element) using the {{htmlattrxref("list","input")}} attribute.</p> + +<p>Once a data list is affiliated with a form widget, its options are used to auto-complete text entered by the user; typically, this is presented to the user as a drop-down box listing possible matches for what they've typed into the input.</p> + +<pre class="brush: html"><label for="myFruit">What's your favorite fruit?</label> +<input type="text" name="myFruit" id="myFruit" list="mySuggestion"> +<datalist id="mySuggestion"> + <option>Apple</option> + <option>Banana</option> + <option>Blackberry</option> + <option>Blueberry</option> + <option>Lemon</option> + <option>Lychee</option> + <option>Peach</option> + <option>Pear</option> +</datalist></pre> + +<div class="note"><strong>Note:</strong> According to <a href="http://www.w3.org/TR/html5/common-input-element-attributes.html#attr-input-list" rel="external" title="http://www.w3.org/TR/html5/common-input-element-attributes.html#attr-input-list">the HTML specification</a>, the {{htmlattrxref("list","input")}} attribute and the {{HTMLElement("datalist")}} element can be used with any kind of widget requiring a user input. However, it is unclear how it should work with controls other than text (color or date for example), and different browsers behave differently from case to case. Because of that, be cautious using this feature with anything but text fields.</div> + +<div><img alt="Screenshots of datalist on several platforms." src="/files/4593/all-datalist.png" style="height: 329px; width: 437px;"></div> + +<div></div> + +<h4 id="Datalist_support_and_fallbacks">Datalist support and fallbacks</h4> + +<p>The {{HTMLElement("datalist")}} element is a very recent addition to HTML forms, so browser support is a bit more limited than what we saw earlier. Most notably, it isn't supported in IE versions below 10, and Safari still doesn't support it at the time of writing.</p> + +<p>To handle this, here is a little trick to provide a nice fallback for those browsers:</p> + +<pre class="brush:html;"><label for="myFruit">What is your favorite fruit? (With fallback)</label> +<input type="text" id="myFruit" name="fruit" list="fruitList"> + +<datalist id="fruitList"> + <label for="suggestion">or pick a fruit</label> + <select id="suggestion" name="altFruit"> + <option>Apple</option> + <option>Banana</option> + <option>Blackberry</option> + <option>Blueberry</option> + <option>Lemon</option> + <option>Lychee</option> + <option>Peach</option> + <option>Pear</option> + </select> +</datalist> +</pre> + +<p>Browsers that support the {{HTMLElement("datalist")}} element will ignore all the elements that are not {{HTMLElement("option")}} elements and will work as expected. On the other hand, browsers that do not support the {{HTMLElement("datalist")}} element will display the label and the select box. Of course, there are other ways to handle the lack of support for the {{HTMLElement("datalist")}} element, but this is the simplest (others tend to require JavaScript).</p> + +<table> + <tbody> + <tr> + <th scope="row">Safari 6</th> + <td><img alt="Screenshot of the datalist element fallback with Safari on Mac OS" src="/files/4583/datalist-safari.png" style="height: 32px; width: 495px;"></td> + </tr> + <tr> + <th scope="row">Firefox 18</th> + <td><img alt="Screenshot of the datalist element with Firefox on Mac OS" src="/files/4581/datalist-firefox-macos.png" style="height: 102px; width: 353px;"></td> + </tr> + </tbody> +</table> + +<h2 id="Checkable_items">Checkable items</h2> + +<p>Checkable items are widgets whose state you can change by clicking on them. There are two kinds of checkable item: the check box and the radio button. Both use the {{htmlattrxref("checked","input")}} attribute to indicate whether the widget is checked by default or not.</p> + +<p>It's worth noting that these widgets do not behave exactly like other form widgets. For most form widgets, once the form is submitted all widgets that have a {{htmlattrxref("name","input")}} attribute are sent, even if no value has been filled out. In the case of checkable items, their values are sent only if they are checked. If they are not checked, nothing is sent, not even their name.</p> + +<div class="note"> +<p><strong>Note</strong>: You can find the examples from this section on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/html/forms/native-form-widgets/checkable-items.html">checkable-items.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/native-form-widgets/checkable-items.html">see it live also</a>).</p> +</div> + +<p>For maximum usability/accessibility, you are advised to surround each list of related items in a {{htmlelement("fieldset")}}, with a {{htmlelement("legend")}} providing an overall description of the list. Each individual pair of {{htmlelement("label")}}/{{htmlelement("input")}} elements should be contained in its own list item (or similar). This is shown in the examples. </p> + +<p>You also need to provide values for these kinds of inputs inside the <code>value</code> attribute if you want them to be meaningful — if no value is provided, check boxes and radio buttons are given a value of <code>on</code>.</p> + +<h3 id="Check_box">Check box</h3> + +<p>A check box is created using the {{HTMLElement("input")}} element with its {{htmlattrxref("type","input")}} attribute set to the value <code>checkbox</code>.</p> + +<pre class="brush: html"><input type="checkbox" checked id="carrots" name="carrots" value="carrots"> +</pre> + +<p>Including the <code>checked</code> attribute makes the checkbox checked automatically when the page loads.</p> + +<p><img alt="Screenshots of check boxes on several platforms." src="/files/4595/all-checkbox.png" style="height: 198px; width: 352px;"></p> + +<h3 id="Radio_button">Radio button</h3> + +<p>A radio button is created using the {{HTMLElement("input")}} element with its {{htmlattrxref("type","input")}} attribute set to the value <code>radio</code>.</p> + +<pre class="brush: html"><input type="radio" checked id="soup" name="meal"></pre> + +<p>Several radio buttons can be tied together. If they share the same value for their {{htmlattrxref("name","input")}} attribute, they will be considered to be in the same group of buttons. Only one button in a given group may be checked at the same time; this means that when one of them is checked all the others automatically get unchecked. When the form is sent, only the value of the checked radio button is sent. If none of them are checked, the whole pool of radio buttons is considered to be in an unknown state and no value is sent with the form.</p> + +<pre class="brush: html"><fieldset> + <legend>What is your favorite meal?</legend> + <ul> + <li> + <label for="soup">Soup</label> + <input type="radio" checked id="soup" name="meal" value="soup"> + </li> + <li> + <label for="curry">Curry</label> + <input type="radio" id="curry" name="meal" value="curry"> + </li> + <li> + <label for="pizza">Pizza</label> + <input type="radio" id="pizza" name="meal" value="pizza"> + </li> + </ul> +</fieldset></pre> + +<p><img alt="Screenshots of radio buttons on several platforms." src="/files/4597/all-radio.png" style="height: 198px; width: 352px;"></p> + +<h2 id="Buttons">Buttons</h2> + +<p>Within HTML forms, there are three kinds of button:</p> + +<dl> + <dt>Submit</dt> + <dd>Sends the form data to the server. For {{HTMLElement("button")}} elements, omitting the <code>type</code> attribute (or an invalid value of <code>type</code>) results in a submit button.</dd> + <dt>Reset</dt> + <dd>Resets all form widgets to their default values.</dd> + <dt>Anonymous</dt> + <dd>Buttons that have no automatic effect but can be customized using JavaScript code.</dd> +</dl> + +<div class="note"> +<p><strong>Note</strong>: You can find the examples from this section on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/html/forms/native-form-widgets/button-examples.html">button-examples.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/native-form-widgets/button-examples.html">see it live also</a>).</p> +</div> + +<p>A button is created using a {{HTMLElement("button")}} element or an {{HTMLElement("input")}} element. It's the value of the {{htmlattrxref("type","input")}} attribute that specifies what kind of button is displayed:</p> + +<h3 id="submit">submit</h3> + +<pre class="brush: html"><button type="submit"> + This a <br><strong>submit button</strong> +</button> + +<input type="submit" value="This is a submit button"></pre> + +<h3 id="reset">reset</h3> + +<pre class="brush: html"><button type="reset"> + This a <br><strong>reset button</strong> +</button> + +<input type="reset" value="This is a reset button"></pre> + +<h3 id="anonymous">anonymous</h3> + +<pre class="brush: html"><button type="button"> + This an <br><strong>anonymous button</strong> +</button> + +<input type="button" value="This is an anonymous button"></pre> + +<p>Buttons always behave the same whether you use a {{HTMLElement("button")}} element or an {{HTMLElement("input")}} element. There are, however, some notable differences:</p> + +<ul> + <li>As you can see from the examples, {{HTMLElement("button")}} elements let you use HTML content in their labels, which are inserted inside the opening and closing <code><button></code> tags. {{HTMLElement("input")}} elements on the other hand are empty elements; their labels are inserted inside <code>value</code> attributes, and therefore only accept plain text content.</li> + <li>With {{HTMLElement("button")}} elements, it's possible to have a value different than the button's label (by setting it inside a <code>value</code> attribute). This isn't reliable in versions of Internet Explorer prior to IE 8.</li> +</ul> + +<p><img alt="Screenshots of buttons on several platforms." src="/files/4599/all-buttons.png" style="height: 235px; width: 464px;"></p> + +<p>Technically speaking, there is almost no difference between a button defined with the {{HTMLElement("button")}} element or the {{HTMLElement("input")}} element. The only noticeable difference is the label of the button itself. Within an {{HTMLElement("input")}} element, the label can only be character data, whereas in a {{HTMLElement("button")}} element, the label can be HTML, so it can be styled accordingly.</p> + +<h2 id="Advanced_form_widgets">Advanced form widgets</h2> + +<p>In this section we cover those widgets that let users input complex or unusual data. This includes exact or approximate numbers, dates and times, or colors.</p> + +<div class="note"> +<p><strong>Note</strong>: You can find the examples from this section on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/html/forms/native-form-widgets/advanced-examples.html">advanced-examples.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/native-form-widgets/advanced-examples.html">see it live also</a>).</p> +</div> + +<h3 id="Numbers">Numbers</h3> + +<p>Widgets for numbers are created with the {{HTMLElement("input")}} element, with its {{htmlattrxref("type","input")}} attribute set to the value <code>number</code>. This control looks like a text field but allows only floating-point numbers, and usually provides some buttons to increase or decrease the value of the widget.</p> + +<p>It's also possible to:</p> + +<ul> + <li>Constrain the value by setting the {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} attributes.</li> + <li>Specify the amount by which the increase and decrease buttons change the widget's value by setting the {{htmlattrxref("step","input")}} attribute.</li> +</ul> + +<h4 id="Example">Example</h4> + +<pre class="brush: html"><input type="number" name="age" id="age" min="1" max="10" step="2"></pre> + +<p>This creates a number widget whose value is restricted to any value between 1 and 10, and whose increase and decrease buttons change its value by 2.</p> + +<p><code>number</code> inputs are not supported in versions of Internet Explorer below 10.</p> + +<h3 id="Sliders">Sliders</h3> + +<p>Another way to pick a number is to use a slider. Visually speaking, sliders are less accurate than text fields, therefore they are used to pick a number whose exact value is not necessarily important.</p> + +<p>A slider is created by using the {{HTMLElement("input")}} with its {{htmlattrxref("type","input")}} attribute set to the value <code>range</code>. It's important to properly configure your slider; to that end, it's highly recommended that you set the {{htmlattrxref("min","input")}}, {{htmlattrxref("max","input")}}, and {{htmlattrxref("step","input")}} attributes.</p> + +<h4 id="Example_2">Example</h4> + +<pre class="brush: html"><input type="range" name="beans" id="beans" min="0" max="500" step="10"></pre> + +<p>This example creates a slider whose value may range between 0 and 500, and whose increment/decrement buttons change the value by +10 and -10.</p> + +<p>One problem with sliders is that they don't offer any kind of visual feedback as to what the current value is. You need to add this yourself with JavaScript, but this is relatively easy to do. In this example we add an empty {{htmlelement("span")}} element, in which we will write the current value of the slider, updating it as it is changed.</p> + +<pre class="brush: html"><label for="beans">How many beans can you eat?</label> +<input type="range" name="beans" id="beans" min="0" max="500" step="10"> +<span class="beancount"></span></pre> + +<p>This can be implemented using some simple JavaScript:</p> + +<pre class="brush: js">var beans = document.querySelector('#beans'); +var count = document.querySelector('.beancount'); + +count.textContent = beans.value; + +beans.oninput = function() { + count.textContent = beans.value; +}</pre> + +<p>Here we store references to the range input and the span in two variables, then we immediately set the span's <code><a href="/en-US/docs/Web/API/Node/textContent">textContent</a></code> to the current <code>value</code> of the input. Finally, we set up an <code>oninput</code> event handler so that every time the range slider is moved, the span <code>textContent</code> is updated to the new input value.</p> + +<p><code>range</code> inputs are not supported in versions of Internet Explorer below 10.</p> + +<h3 id="Date_and_time_picker">Date and time picker</h3> + +<p>Gathering date and time values has traditionally been a nightmare for web developers. HTML5 brings some enhancements here by providing a special control to handle this specific kind of data.</p> + +<p>A date and time control is created using the {{HTMLElement("input")}} element and an appropriate value for the {{htmlattrxref("type","input")}} attribute, depending on whether you wish to collect dates, times, or both.</p> + +<h4 id="datetime-local"><code>datetime-local</code></h4> + +<p>This creates a widget to display and pick a date with time, but without any specific time zone information.</p> + +<pre class="brush: html"><input type="datetime-local" name="datetime" id="datetime"></pre> + +<h4 id="month"><code>month</code></h4> + +<p>This creates a widget to display and pick a month with a year.</p> + +<pre class="brush: html"><input type="month" name="month" id="month"></pre> + +<h4 id="time"><code>time</code></h4> + +<p>This creates a widget to display and pick a time value.</p> + +<pre class="brush: html"><input type="time" name="time" id="time"></pre> + +<h4 id="week"><code>week</code></h4> + +<p>This creates a widget to display and pick a week number and its year.</p> + +<pre class="brush: html"><input type="week" name="week" id="week"></pre> + +<p>All date and time control can be constrained using the {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} attributes.</p> + +<pre class="brush: html"><label for="myDate">When are you available this summer?</label> +<input type="date" name="myDate" min="2013-06-01" max="2013-08-31" id="myDate"></pre> + +<p>Warning — The date and time widgets don't have the deepest support. At the moment, Chrome, Edge, Firefox, and Opera support them well, but there is no support in Internet Explorer and Safari has patchy support.</p> + +<h3 id="Color_picker">Color picker</h3> + +<p>Colors are always a bit difficult to handle. There are many ways to express them: RGB values (decimal or hexadecimal), HSL values, keywords, etc. The color widget lets users pick a color in both textual and visual ways.</p> + +<p>A color widget is created using the {{HTMLElement("input")}} element with its {{htmlattrxref("type","input")}} attribute set to the value <code>color</code>.</p> + +<pre class="brush: html"><input type="color" name="color" id="color"></pre> + +<p>Warning — Color widget support it currently not very good. There is no support in Internet Explorer, and Safari currently doesn't support it either. The other major browsers do support it.</p> + +<h2 id="Other_widgets">Other widgets</h2> + +<p>There are a few other widgets that cannot be easily classified due to their very specific behaviors, but which are still very useful.</p> + +<div class="note"> +<p><strong>Note</strong>: You can find the examples from this section on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/html/forms/native-form-widgets/other-examples.html">other-examples.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/native-form-widgets/other-examples.html">see it live also</a>).</p> +</div> + +<h3 id="File_picker">File picker</h3> + +<p>HTML forms are able to send files to a server; this specific action is detailed in the article <a href="/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data" title="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data">Sending and retrieving form data</a>. The file picker widget is how the user can choose one or more files to send.</p> + +<p>To create a file picker widget, you use the {{HTMLElement("input")}} element with its {{htmlattrxref("type","input")}} attribute set to <code>file</code>. The types of files that are accepted can be constrained using the {{htmlattrxref("accept","input")}} attribute. In addition, if you want to let the user pick more than one file, you can do so by adding the {{htmlattrxref("multiple","input")}} attribute.</p> + +<h4 id="Example_3">Example</h4> + +<p>In this example, a file picker is created that requests graphic image files. The user is allowed to select multiple files in this case.</p> + +<pre class="brush: html"><input type="file" name="file" id="file" accept="image/*" multiple></pre> + +<h3 id="Hidden_content">Hidden content</h3> + +<p>It's sometimes convenient for technical reasons to have pieces of data that are sent with a form but not displayed to the user. To do this, you can add an invisible element in your form. Use an {{HTMLElement("input")}} with its {{htmlattrxref("type","input")}} attribute set to the value <code>hidden</code>.</p> + +<p>If you create such an element, it's required to set its <code>name</code> and <code>value</code> attributes:</p> + +<pre class="brush: html"><input type="hidden" id="timestamp" name="timestamp" value="1286705410"></pre> + +<h3 id="Image_button">Image button</h3> + +<p>The <strong>image button</strong> control is one which is displayed exactly like an {{HTMLElement("img")}} element, except that when the user clicks on it, it behaves like a submit button (see above).</p> + +<p>An image button is created using an {{HTMLElement("input")}} element with its {{htmlattrxref("type","input")}} attribute set to the value <code>image</code>. This element supports exactly the same set of attributes as the {{HTMLElement("img")}} element, plus all the attributes supported by other form buttons.</p> + +<pre class="brush: html"><input type="image" alt="Click me!" src="my-img.png" width="80" height="30" /></pre> + +<p>If the image button is used to submit the form, this widget doesn't submit its value; instead the X and Y coordinates of the click on the image are submitted (the coordinates are relative to the image, meaning that the upper-left corner of the image represents the coordinate 0, 0). The coordinates are sent as two key/value pairs:</p> + +<ul> + <li>The X value key is the value of the {{htmlattrxref("name","input")}} attribute followed by the string "<em>.x</em>".</li> + <li>The Y value key is the value of the {{htmlattrxref("name","input")}} attribute followed by the string "<em>.y</em>".</li> +</ul> + +<p>So for example when you click on the image of this widget, you are sent to a URL like the following:</p> + +<pre>http://foo.com?pos.x=123&pos.y=456</pre> + +<p>This is a very convenient way to build a "hot map". How these values are sent and retrieved is detailed in the <a href="/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data" title="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data"><span>Sending and retrieving form data</span></a> article.</p> + +<h3 id="Meters_and_progress_bars">Meters and progress bars</h3> + +<p>Meters and progress bars are visual representations of numeric values.</p> + +<h4 id="Progress">Progress</h4> + +<p>A progress bar represents a value that changes over time up to a maximum value specified by the {{htmlattrxref("max","progress")}} attribute. Such a bar is created using a {{ HTMLElement("progress")}} element.</p> + +<pre class="brush: html"><progress max="100" value="75">75/100</progress></pre> + +<p>This is for implementing anything requiring progress reporting, such as the percentage of total files downloaded, or the number of questions filled in on a questionnaire.</p> + +<p>The content inside the {{HTMLElement("progress")}} element is a fallback for browsers that don't support the element and for assistive technologies to vocalize it.</p> + +<h4 id="Meter">Meter</h4> + +<p>A meter bar represents a fixed value in a range delimited by a {{htmlattrxref("min","meter")}} and a {{htmlattrxref("max","meter")}} value. This value is visualy rendered as a bar, and to know how this bar looks, we compare the value to some other set values:</p> + +<ul> + <li>The {{htmlattrxref("low","meter")}} and {{htmlattrxref("high","meter")}} values divide the range in three parts: + <ul> + <li>The lower part of the range is between the {{htmlattrxref("min","meter")}} and {{htmlattrxref("low","meter")}} values (including those values).</li> + <li>The medium part of the range is between the {{htmlattrxref("low","meter")}} and {{htmlattrxref("high","meter")}} values (excluding those values).</li> + <li>The higher part of the range is between the {{htmlattrxref("high","meter")}} and {{htmlattrxref("max","meter")}} values (including those values).</li> + </ul> + </li> + <li>The {{htmlattrxref("optimum","meter")}} value defines the optimum value for the {{HTMLElement("meter")}} element. In conjuction with the {{htmlattrxref("low","meter")}} and {{htmlattrxref("high","meter")}} value, it defines which part of the range is prefered: + <ul> + <li>If the {{htmlattrxref("optimum","meter")}} value is in the lower part of the range, the lower range is considered to be the prefered part, the medium range is considered to be the average part and the higher range is considered to be the worst part.</li> + <li>If the {{htmlattrxref("optimum","meter")}} value is in the medium part of the range, the lower range is considered to be an average part, the medium range is considered to be the prefered part and the higher range is considered to be average as well.</li> + <li>If the {{htmlattrxref("optimum","meter")}} value is in the higher part of the range, the lower range is considered to be the worst part, the medium range is considered to be the average part and the higher range is considered to be the prefered part.</li> + </ul> + </li> +</ul> + +<p>All browsers that implement the {{HTMLElement("meter")}} element use those values to change the color of the meter bar:</p> + +<ul> + <li>If the current value is in the prefered part of the range, the bar is green.</li> + <li>If the current value is in the average part of the range, the bar is yellow.</li> + <li>If the current value is in the worst part of the range, the bar is red.</li> +</ul> + +<p>Such a bar is created using a {{HTMLElement("meter")}} element. This is for implementing any kind of meter, for example a bar showing total space used on a disk, which turns red when it starts to get full.</p> + +<pre class="brush: html"><meter min="0" max="100" value="75" low="33" high="66" optimum="50">75</meter></pre> + +<p>The content inside the {{HTMLElement("meter")}} element is a fallback for browsers that don't support the element and for assistive technologies to vocalize it.</p> + +<p>Support for progress and meter is fairly good — there is no support in Internet Explorer, but other browsers support it well.</p> + +<h2 id="Conclusion">Conclusion</h2> + +<p>As you'll have seen above, there are a lot of different types of available form elements — you don't need to remember all of these details at once, and can return to this article as often as you like to check up on details.</p> + +<h2 id="See_also">See also</h2> + +<p>To dig into the different form widgets, there are some useful external resources you should check out:</p> + +<ul> + <li><a href="http://wufoo.com/html5/" rel="external" title="http://wufoo.com/html5/">The Current State of HTML5 Forms</a> by Wufoo</li> + <li><a href="http://www.quirksmode.org/html5/inputs.html" rel="external" title="http://www.quirksmode.org/html5/inputs.html">HTML5 Tests - inputs</a> on Quirksmode (also <a href="http://www.quirksmode.org/html5/inputs_mobile.html" rel="external" title="http://www.quirksmode.org/html5/inputs_mobile.html">available for mobile</a> browsers)</li> +</ul> + +<p>{{PreviousMenuNext("Learn/HTML/Forms/How_to_structure_an_HTML_form", "Learn/HTML/Forms/Sending_and_retrieving_form_data", "Learn/HTML/Forms")}}</p> + + + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form">Your first HTML form</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form">How to structure an HTML form</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/The_native_form_widgets">The native form widgets</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data">Sending form data</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Form_validation">Form data validation</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/How_to_build_custom_form_widgets">How to build custom form widgets</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript">Sending forms through JavaScript</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/HTML_forms_in_legacy_browsers">HTML forms in legacy browsers</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Styling_HTML_forms">Styling HTML forms</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Advanced_styling_for_HTML_forms">Advanced styling for HTML forms</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Property_compatibility_table_for_form_widgets">Property compatibility table for form widgets</a></li> +</ul> diff --git a/files/pt-br/learn/forms/form_validation/index.html b/files/pt-br/learn/forms/form_validation/index.html new file mode 100644 index 0000000000..7f9146d0a4 --- /dev/null +++ b/files/pt-br/learn/forms/form_validation/index.html @@ -0,0 +1,813 @@ +--- +title: Form data validation +slug: Web/Guide/HTML/Forms/Form_validation +translation_of: Learn/Forms/Form_validation +--- +<div>{{LearnSidebar}}{{PreviousMenuNext("Learn/HTML/Forms/Sending_and_retrieving_form_data", "Learn/HTML/Forms/How_to_build_custom_form_widgets", "Learn/HTML/Forms")}}</div> + +<p class="summary">A validação de formulário nos ajuda a garantir que os usuários preencham os formulários no formato correto, garantindo que os dados enviados funcionem com êxito em nossos aplicativos. Este artigo apresentará conceitos e exemplos básicos sobre validação de formulário. Para mais informações adicionais, consulte o <a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">Constraint validation guide</a>.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Pré-requisitos:</th> + <td>Conhecimento em informática, uma compreensão razoável de <a href="/en-US/docs/Learn/HTML">HTML</a>, <a href="/en-US/docs/Learn/CSS">CSS</a>, e <a href="/en-US/docs/Learn/JavaScript">JavaScript</a>.</td> + </tr> + <tr> + <th scope="row">Objetivo:</th> + <td>Entender o que é validação de formulário, por que é importante e aplicação de várias técnicas para implementá-lo.</td> + </tr> + </tbody> +</table> + +<h2 id="O_que_é_validação_de_formulário">O que é validação de formulário?</h2> + +<p>Vá a qualquer site popular com um formulário de registro, e perceberá que eles dão feedback quando você não insere seus dados no formato esperado. Você receberá mensagens como:</p> + +<ul> + <li>"Sua senha precisa ter entre 8 e 30 caracteres e conter uma letra maiúscula, um símbolo e um número"</li> + <li>"Por favor, digite seu número de telefone no formato xxx-xxxx" (ele impõe três números seguidos por um traço, seguido por quatro números)</li> + <li>"Por favor insira um endereço de email válido" (se a sua entrada não estiver no formato "email@email.com")</li> + <li>"Este campo é obrigatório" (você não pode deixar este campo em branco)</li> +</ul> + +<p>Isso é chamado de validação de formulário - quando você insere dados, o aplicativo da Web faz a verificação para ver se os dados estão corretos. Se estiver correto, o aplicativo permite que os dados sejam enviados ao servidor e (geralmente) salvos em um banco de dados; se não, você receberá uma mensagem de erro explicando quais correções precisam ser feitas. A validação de formulários pode ser implementada de várias maneiras diferentes.</p> + +<p><br> + Queremos tornar o preenchimento de formulários da web o mais fácil possível. Então, por que insistimos em validar nossos formulários? Existem três razões principais:</p> + +<ul> + <li><strong>Nos queremos que o dado correto e no formato correto </strong> — nossa aplicação não irá trabalhar de forma correta se os dados dos nossos usuarios estivem armazenados em formato incorreto, ou quando esses dados são omitidos.</li> + <li><strong>Quemos proteger os dados dos nossos usuários</strong> — Forçarnosos usuários a fornecer senhas seguras facilita na proteção das informações da conta do usuário.</li> + <li><strong>Queremos proteger nos mesmos</strong> — Existem diversas maneiras de um usuário malicioso usar formulários desprotegidos para danificar nossa aplicação (veja <a href="/en-US/docs/Learn/Server-side/First_steps/Website_security">Website security</a>).<br> + {{warning("Nunca confie nos dados passados do cliente para o servidor. Mesmo que seu formulário seja validado de maneira correta e previna a má formação de inputs no lado do cliente, um usuário malicioso ainda pode roubar o request da conexão.")}}</li> +</ul> + +<h3 id="Different_types_of_form_validation">Different types of form validation</h3> + +<p>There are two different types of form validation which you'll encounter on the web:</p> + +<ul> + <li><strong>Client-side validation</strong> is validation that occurs in the browser before the data has been submitted to the server. This is more user-friendly than server-side validation as it gives an instant response. This can be further subdivided: + + <ul> + <li><strong>JavaScript</strong> validation is coded using JavaScript. It is completely customizable.</li> + <li><strong>Built-in form validation</strong> using HTML5 form validation features. This generally does not require JavaScript. Built-in form validation has better performance, but it is not as customizable as JavaScript.</li> + </ul> + </li> + <li><strong>Server-side validation</strong> is validation which occurs on the server after the data has been submitted. Server-side code is used to validate the data before it is saved into the database. If the data fails authentication, a response is sent back to the client to tell the user what corrections to make. Server-side validation is not as user-friendly as client-side validation, as it does not provide errors until the entire form has been submitted. However, server-side validation is your application's last line of defence against incorrect or even malicious data. All popular <a href="/en-US/docs/Learn/Server-side/First_steps/Web_frameworks">server-side frameworks</a> have features for <strong>validating</strong> and <strong>sanitizing</strong> data (making it safe).</li> +</ul> + +<p>In the real world, developers tend to use a combination of client-side and server-side validation.</p> + +<h2 id="Using_built-in_form_validation">Using built-in form validation</h2> + +<p>One of the features of <a href="/en-US/docs/HTML/HTML5">HTML5</a> is the ability to validate most user data without relying on scripts. This is done by using <a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes">validation attributes</a> on form elements, which allow you to specify rules for a form input like whether a value needs to be filled in, the minimum and maximum length of the data, whether it needs to be a number, an email address, or something else, and a pattern that it must match. If the entered data follows all the specified rules, it is considered valid; if not, it is considered invalid.</p> + +<p>When an element is valid:</p> + +<ul> + <li>The element matches the {{cssxref(":valid")}} CSS pseudo-class; this will let you apply a specific style to valid elements.</li> + <li>If the user tries to send the data, the browser will submit the form, provided there is nothing else stopping it from doing so (e.g., JavaScript).</li> +</ul> + +<p>When an element is invalid:</p> + +<ul> + <li>The element matches the {{cssxref(":invalid")}} CSS pseudo-class; this will let you apply a specific style to invalid elements.</li> + <li>If the user tries to send the data, the browser will block the form and display an error message.</li> +</ul> + +<h3 id="Validation_constraints_on_input_elements_—_starting_simple">Validation constraints on input elements — starting simple</h3> + +<p>In this section, we'll look at some of the different HTML5 features that can be used to validate {{HTMLElement("input")}} elements.</p> + +<p>Let's start with a simple example — an input that allows you to choose your favorite fruit out of a choice of banana or cherry. This involves a simple text {{HTMLElement("input")}} with a matching label, and a submit {{htmlelement("button")}}. You can find the source code on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/html/forms/form-validation/fruit-start.html">fruit-start.html</a>, and a live example below:</p> + +<div class="hidden"> +<h6 id="Hidden_code">Hidden code</h6> + +<pre class="brush: html notranslate"><form> + <label for="choose">Would you prefer a banana or cherry?</label> + <input id="choose" name="i_like"> + <button>Submit</button> +</form></pre> + +<pre class="brush: css notranslate">input:invalid { + border: 2px dashed red; +} + +input:valid { + border: 2px solid black; +}</pre> +</div> + +<p>{{EmbedLiveSample("Hidden_code", "100%", 50)}}</p> + +<p>To begin with, make a copy of <code>fruit-start.html</code> in a new directory on your hard drive.</p> + +<h3 id="The_required_attribute">The required attribute</h3> + +<p>The simplest HTML5 validation feature to use is the {{htmlattrxref("required", "input")}} attribute — if you want to make an input mandatory, you can mark the element using this attribute. When this attribute is set, the form won't submit (and will display an error message) when the input is empty (the input will also be considered invalid).</p> + +<p>Add a <code>required</code> attribute to your input, as shown below:</p> + +<pre class="brush: html notranslate"><form> + <label for="choose">Would you prefer a banana or cherry?</label> + <input id="choose" name="i_like" required> + <button>Submit</button> +</form></pre> + +<p>Also, take note of the CSS included in the example file:</p> + +<pre class="brush: css notranslate">input:invalid { + border: 2px dashed red; +} + +input:valid { + border: 2px solid black; +}</pre> + +<p>This causes the input to have a bright red dashed border when it is invalid, and a more subtle black border when valid. Try out the new behaviour in the example below:</p> + +<p>{{EmbedLiveSample("The_required_attribute", "100%", 80)}}</p> + +<h3 id="Validating_against_a_regular_expression">Validating against a regular expression</h3> + +<p>Another very common validation feature is the {{htmlattrxref("pattern","input")}} attribute, which expects a <a href="/en-US/docs/JavaScript/Guide/Regular_Expressions">Regular Expression</a> as its value. A regular expression (regex) is a pattern that can be used to match character combinations in text strings, so they are ideal for form validation (as well as a variety of other uses in JavaScript).</p> + +<p>Regexs are quite complex, and we do not intend to teach you them exhaustively in this article. Below are some examples to give you a basic idea of how they work:</p> + +<ul> + <li><code>a</code> — matches one character that is <code>a</code> (not <code>b</code>, not <code>aa</code>, etc.)</li> + <li><code>abc</code> — matches <code>a</code>, followed by <code>b</code>, followed by <code>c</code>.</li> + <li><code>a|b</code> — matches one character that is <code>a</code> or <code>b</code>.</li> + <li><code>abc|xyz</code> — matches exactly <code>abc</code> or exactly <code>xyz</code> (but not <code>abcxyz</code>, or <code>a</code> or <code>y</code>, etc).</li> + <li>There are many more possibilities that we don't need to cover here.</li> +</ul> + +<p>Anyway, let's implement an example — update your HTML to add a <code>pattern</code> attribute, like so:</p> + +<pre class="brush: html notranslate"><form> + <label for="choose">Would you prefer a banana or a cherry?</label> + <input id="choose" name="i_like" required pattern="banana|cherry"> + <button>Submit</button> +</form></pre> + +<div class="hidden"> +<pre class="brush: css notranslate">input:invalid { + border: 2px dashed red; +} + +input:valid { + border: 2px solid black; +}</pre> +</div> + +<p>{{EmbedLiveSample("Validating_against_a_regular_expression", "100%", 80)}}</p> + +<p>In this example, the {{HTMLElement("input")}} element accepts one of two possible values: the string "banana" or the string "cherry".</p> + +<p>At this point, try changing the value inside the <code>pattern</code> attribute to equal some of the examples you saw earlier, and look at how that affects the values you can enter to make the input value valid. Try writing some of your own, and see how you get on! Try to make them fruit-related where possible, so your examples make sense!</p> + +<div class="note"> +<p><strong>Note:</strong> Some {{HTMLElement("input")}} element types do not need a {{htmlattrxref("pattern","input")}} attribute to be validated. Specifying the <code>email</code> type for example validates the inputted value against a regular expression matching a well-formed email address (or a comma-separated list of email addresses if it has the {{htmlattrxref("multiple","input")}} attribute). As a further example, fields with the <code>url</code> type automatically require a properly-formed URL.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: The {{HTMLElement("textarea")}} element does not support the {{htmlattrxref("pattern","input")}} attribute.</p> +</div> + +<h3 id="Constraining_the_length_of_your_entries">Constraining the length of your entries</h3> + +<p>All text fields created by {{HTMLElement("input")}} or {{HTMLElement("textarea")}} can be constrained in size using the {{htmlattrxref("minlength","input")}} and {{htmlattrxref("maxlength","input")}} attributes. A field is invalid if its value is shorter than the {{htmlattrxref("minlength","input")}} value or longer than the {{htmlattrxref("maxlength","input")}} value. Browsers often don't let the user type a longer value than expected into text fields anyway, but it is useful to have this fine-grained control available.</p> + +<p>For number fields (i.e. <code><input type="number"></code>), the {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} attributes also provide a validation constraint. If the field's value is lower than the {{htmlattrxref("min","input")}} attribute or higher than the {{htmlattrxref("max","input")}} attribute, the field will be invalid.</p> + +<p>Let's look at another example. Create a new copy of the <a href="https://github.com/mdn/learning-area/blob/master/html/forms/form-validation/fruit-start.html">fruit-start.html</a> file.</p> + +<p>Now delete the contents of the <code><body></code> element, and replace it with the following:</p> + +<pre class="brush: html notranslate"><form> + <div> + <label for="choose">Would you prefer a banana or a cherry?</label> + <input type="text" id="choose" name="i_like" required minlength="6" maxlength="6"> + </div> + <div> + <label for="number">How many would you like?</label> + <input type="number" id="number" name="amount" value="1" min="1" max="10"> + </div> + <div> + <button>Submit</button> + </div> +</form></pre> + +<ul> + <li>Here you'll see that we've given the <code>text</code> field a <code>minlength</code> and <code>maxlength</code> of 6 — the same length as banana and cherry. Entering less characters will show as invalid, and entering more is not possible in most browsers.</li> + <li>We've also given the <code>number</code> field a <code>min</code> of 1 and a <code>max</code> of 10 — entered numbers outside this range will show as invalid, and you won't be able to use the increment/decrement arrows to move the value outside this range.</li> +</ul> + +<div class="hidden"> +<pre class="notranslate">input:invalid { + border: 2px dashed red; +} + +input:valid { + border: 2px solid black; +} + +div { + margin-bottom: 10px; +}</pre> +</div> + +<p>Here is the example running live:</p> + +<p>{{EmbedLiveSample("Constraining_the_length_of_your_entries", "100%", 100)}}</p> + +<div class="note"> +<p><strong>Note</strong>: <code><input type="number"></code> (and other types, like <code>range</code>) can also take a {{htmlattrxref("step", "input")}} attribute, which specifies what increment the value will go up or down by when the input controls are used (like the up and down number buttons).</p> +</div> + +<h3 id="Full_example">Full example</h3> + +<p>Here is a full example to show off usage of HTML's built-in validation features:</p> + +<pre class="brush: html notranslate"><form> + <p> + <fieldset> + <legend>Title<abbr title="This field is mandatory">*</abbr></legend> + <input type="radio" required name="title" id="r1" value="Mr"><label for="r1">Mr.</label> + <input type="radio" required name="title" id="r2" value="Ms"><label for="r2">Ms.</label> + </fieldset> + </p> + <p> + <label for="n1">How old are you?</label> + <!-- The pattern attribute can act as a fallback for browsers which + don't implement the number input type but support the pattern attribute. + Please note that browsers that support the pattern attribute will make it + fail silently when used with a number field. + Its usage here acts only as a fallback --> + <input type="number" min="12" max="120" step="1" id="n1" name="age" + pattern="\d+"> + </p> + <p> + <label for="t1">What's your favorite fruit?<abbr title="This field is mandatory">*</abbr></label> + <input type="text" id="t1" name="fruit" list="l1" required + pattern="[Bb]anana|[Cc]herry|[Aa]pple|[Ss]trawberry|[Ll]emon|[Oo]range"> + <datalist id="l1"> + <option>Banana</option> + <option>Cherry</option> + <option>Apple</option> + <option>Strawberry</option> + <option>Lemon</option> + <option>Orange</option> + </datalist> + </p> + <p> + <label for="t2">What's your e-mail?</label> + <input type="email" id="t2" name="email"> + </p> + <p> + <label for="t3">Leave a short message</label> + <textarea id="t3" name="msg" maxlength="140" rows="5"></textarea> + </p> + <p> + <button>Submit</button> + </p> +</form></pre> + +<pre class="brush: css notranslate">body { + font: 1em sans-serif; + padding: 0; + margin : 0; +} + +form { + max-width: 200px; + margin: 0; + padding: 0 5px; +} + +p > label { + display: block; +} + +input[type=text], +input[type=email], +input[type=number], +textarea, +fieldset { +/* required to properly style form + elements on WebKit based browsers */ + -webkit-appearance: none; + + width : 100%; + border: 1px solid #333; + margin: 0; + + font-family: inherit; + font-size: 90%; + + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +input:invalid { + box-shadow: 0 0 5px 1px red; +} + +input:focus:invalid { + box-shadow: none; +}</pre> + +<p>{{EmbedLiveSample("Full_example", "100%", 420)}}</p> + +<p>See <a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes">Validation-related attributes</a> for a complete list of attributes that can be used to constrain input values, and the input types that support them.</p> + +<h3 id="Customized_error_messages">Customized error messages</h3> + +<p>As seen in the examples above, each time the user tries to submit an invalid form, the browser displays an error message. The way this message is displayed depends on the browser.</p> + +<p>These automated messages have two drawbacks:</p> + +<ul> + <li>There is no standard way to change their look and feel with CSS.</li> + <li>They depend on the browser locale, which means that you can have a page in one language but an error message displayed in another language.</li> +</ul> + +<table> + <caption>French versions of feedback messages on an English page</caption> + <thead> + <tr> + <th scope="col">Browser</th> + <th scope="col">Rendering</th> + </tr> + </thead> + <tbody> + <tr> + <td>Firefox 17 (Windows 7)</td> + <td><img alt="Example of an error message with Firefox in French on an English page" src="/files/4329/error-firefox-win7.png" style="height: 97px; width: 228px;"></td> + </tr> + <tr> + <td>Chrome 22 (Windows 7)</td> + <td><img alt="Example of an error message with Chrome in French on an English page" src="/files/4327/error-chrome-win7.png" style="height: 96px; width: 261px;"></td> + </tr> + <tr> + <td>Opera 12.10 (Mac OSX)</td> + <td><img alt="Example of an error message with Opera in French on an English page" src="/files/4331/error-opera-macos.png" style="height: 83px; width: 218px;"></td> + </tr> + </tbody> +</table> + +<p>To customize the appearance and text of these messages, you must use JavaScript; there is no way to do it using just HTML and CSS.</p> + +<p>HTML5 provides the <a href="/en-US/docs/Web/API/Constraint_validation" rel="external">constraint validation API</a> to check and customize the state of a form element. Among other things, it's possible to change the text of the error message. Let's see a quick example:</p> + +<pre class="brush: html notranslate"><form> + <label for="mail">I would like you to provide me an e-mail</label> + <input type="email" id="mail" name="mail"> + <button>Submit</button> +</form></pre> + +<p>In JavaScript, you call the <a href="/en-US/docs/HTML/HTML5/Constraint_validation#Constraint_API's_element.setCustomValidity()"><code>setCustomValidity()</code></a> method:</p> + +<pre class="brush: js notranslate">var email = document.getElementById("mail"); + +email.addEventListener("input", function (event) { + if (email.validity.typeMismatch) { + email.setCustomValidity("I expect an e-mail, darling!"); + } else { + email.setCustomValidity(""); + } +});</pre> + +<p>{{EmbedLiveSample("Customized_error_messages", "100%", 80)}}</p> + +<h2 id="Validating_forms_using_JavaScript">Validating forms using JavaScript</h2> + +<p>If you want to take control over the look and feel of native error messages, or if you want to deal with browsers that do not support HTML's built-in form validation, you must use JavaScript.</p> + +<h3 id="The_constraint_validation_API">The constraint validation API</h3> + +<p>More and more browsers now support the constraint validation API, and it's becoming reliable. This API consists of a set of methods and properties available on specific form element interfaces:</p> + +<ul> + <li><a href="/en-US/docs/Web/API/HTMLButtonElement">HTMLButtonElement</a></li> + <li><a href="/en-US/docs/Web/API/HTMLFieldSetElement">HTMLFieldSetElement</a></li> + <li><a href="/en-US/docs/Web/API/HTMLInputElement">HTMLInputElement</a></li> + <li><a href="/en-US/docs/Web/API/HTMLOutputElement">HTMLOutputElement</a></li> + <li><a href="/en-US/docs/Web/API/HTMLSelectElement">HTMLSelectElement</a></li> + <li><a href="/en-US/docs/Web/API/HTMLTextAreaElement">HTMLTextAreaElement</a></li> +</ul> + +<h4 id="Constraint_validation_API_properties">Constraint validation API properties</h4> + +<table> + <thead> + <tr> + <th scope="col">Property</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>validationMessage</code></td> + <td>A localized message describing the validation constraints that the control does not satisfy (if any), or the empty string if the control is not a candidate for constraint validation (<code>willValidate</code> is <code>false</code>), or the element's value satisfies its constraints.</td> + </tr> + <tr> + <td><code>validity</code></td> + <td>A {{domxref("ValidityState")}} object describing the validity state of the element. See that article for details of possible validity states.</td> + </tr> + <tr> + <td><code>willValidate</code></td> + <td>Returns <code>true</code> if the element will be validated when the form is submitted; <code>false</code> otherwise.</td> + </tr> + </tbody> +</table> + +<h4 id="Constraint_validation_API_methods">Constraint validation API methods</h4> + +<table> + <thead> + <tr> + <th scope="col">Method</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>checkValidity()</code></td> + <td>Returns <code>true</code> if the element's value has no validity problems; <code>false</code> otherwise. If the element is invalid, this method also causes an {{event("invalid")}} event at the element.</td> + </tr> + <tr> + <td>{{domxref("HTMLFormElement.reportValidity()")}}</td> + <td>Returns <code>true</code> if the element or its child controls satisfy validation constraints. When <code>false</code> is returned, cancelable {{event("invalid")}} events are fired for each invalid element and validation problems are reported to the user.</td> + </tr> + <tr> + <td><code>setCustomValidity(<em>message</em>)</code></td> + <td>Adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is displayed. This lets you use JavaScript code to establish a validation failure other than those offered by the standard constraint validation API. The message is shown to the user when reporting the problem.<br> + <br> + If the argument is the empty string, the custom error is cleared.</td> + </tr> + </tbody> +</table> + +<p>For legacy browsers, it's possible to use a <a href="https://hyperform.js.org/" rel="external">polyfill such as Hyperform </a> to compensate for the lack of support for the constraint validation API. Since you're already using JavaScript, using a polyfill isn't an added burden to your Web site or Web application's design or implementation.</p> + +<h4 id="Example_using_the_constraint_validation_API">Example using the constraint validation API</h4> + +<p>Let's see how to use this API to build custom error messages. First, the HTML:</p> + +<pre class="brush: html notranslate"><form novalidate> + <p> + <label for="mail"> + <span>Please enter an email address:</span> + <input type="email" id="mail" name="mail"> + <span class="error" aria-live="polite"></span> + </label> + </p> + <button>Submit</button> +</form></pre> + +<p>This simple form uses the {{htmlattrxref("novalidate","form")}} attribute to turn off the browser's automatic validation; this lets our script take control over validation. However, this doesn't disable support for the constraint validation API nor the application of the CSS pseudo-class {{cssxref(":valid")}}, {{cssxref(":invalid")}}, {{cssxref(":in-range")}} and {{cssxref(":out-of-range")}} classes. That means that even though the browser doesn't automatically check the validity of the form before sending its data, you can still do it yourself and style the form accordingly.</p> + +<p>The <a href="/en-US/docs/Accessibility/ARIA/ARIA_Live_Regions"><code>aria-live</code></a> attribute makes sure that our custom error message will be presented to everyone, including those using assistive technologies such as screen readers.</p> + +<h5 id="CSS">CSS</h5> + +<p>This CSS styles our form and the error output to look more attractive.</p> + +<pre class="brush: css notranslate">/* This is just to make the example nicer */ +body { + font: 1em sans-serif; + padding: 0; + margin : 0; +} + +form { + max-width: 200px; +} + +p * { + display: block; +} + +input[type=email]{ + -webkit-appearance: none; + + width: 100%; + border: 1px solid #333; + margin: 0; + + font-family: inherit; + font-size: 90%; + + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +/* This is our style for the invalid fields */ +input:invalid{ + border-color: #900; + background-color: #FDD; +} + +input:focus:invalid { + outline: none; +} + +/* This is the style of our error messages */ +.error { + width : 100%; + padding: 0; + + font-size: 80%; + color: white; + background-color: #900; + border-radius: 0 0 5px 5px; + + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.error.active { + padding: 0.3em; +}</pre> + +<h5 id="JavaScript">JavaScript</h5> + +<p>The following JavaScript code handles the custom error validation.</p> + +<pre class="brush: js notranslate">// There are many ways to pick a DOM node; here we get the form itself and the email +// input box, as well as the span element into which we will place the error message. + +var form = document.getElementsByTagName('form')[0]; +var email = document.getElementById('mail'); +var error = document.querySelector('.error'); + +email.addEventListener("input", function (event) { + // Each time the user types something, we check if the + // email field is valid. + if (email.validity.valid) { + // In case there is an error message visible, if the field + // is valid, we remove the error message. + error.innerHTML = ""; // Reset the content of the message + error.className = "error"; // Reset the visual state of the message + } +}, false); +form.addEventListener("submit", function (event) { + // Each time the user tries to send the data, we check + // if the email field is valid. + if (!email.validity.valid) { + + // If the field is not valid, we display a custom + // error message. + error.innerHTML = "I expect an e-mail, darling!"; + error.className = "error active"; + // And we prevent the form from being sent by canceling the event + event.preventDefault(); + } +}, false);</pre> + +<p>Here is the live result:</p> + +<p>{{EmbedLiveSample("Example_using_the_constraint_validation_API", "100%", 130)}}</p> + +<p>The constraint validation API gives you a powerful tool to handle form validation, letting you have enormous control over the user interface above and beyond what you can do just with HTML and CSS alone.</p> + +<h3 id="Validating_forms_without_a_built-in_API">Validating forms without a built-in API</h3> + +<p>Sometimes, such as with legacy browsers or <a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets">custom widgets</a>, you will not be able to (or will not want to) use the constraint validation API. In that case, you're still able to use JavaScript to validate your form. Validating a form is more a question of user interface than real data validation.</p> + +<p>To validate a form, you have to ask yourself a few questions:</p> + +<dl> + <dt>What kind of validation should I perform?</dt> + <dd>You need to determine how to validate your data: string operations, type conversion, regular expressions, etc. It's up to you. Just remember that form data is always text and is always provided to your script as strings.</dd> + <dt>What should I do if the form does not validate?</dt> + <dd>This is clearly a UI matter. You have to decide how the form will behave: Does the form send the data anyway? Should you highlight the fields which are in error? Should you display error messages?</dd> + <dt>How can I help the user to correct invalid data?</dt> + <dd>In order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs. You should offer up-front suggestions so they know what's expected, as well as clear error messages. If you want to dig into form validation UI requirements, there are some useful articles you should read: + <ul> + <li>SmashingMagazine: <a href="http://uxdesign.smashingmagazine.com/2012/06/27/form-field-validation-errors-only-approach/" rel="external">Form-Field Validation: The Errors-Only Approach</a></li> + <li>SmashingMagazine: <a href="http://www.smashingmagazine.com/2009/07/07/web-form-validation-best-practices-and-tutorials/" rel="external">Web Form Validation: Best Practices and Tutorials</a></li> + <li>Six Revision: <a href="http://sixrevisions.com/user-interface/best-practices-for-hints-and-validation-in-web-forms/" rel="external">Best Practices for Hints and Validation in Web Forms</a></li> + <li>A List Apart: <a href="http://www.alistapart.com/articles/inline-validation-in-web-forms/" rel="external">Inline Validation in Web Forms</a></li> + </ul> + </dd> +</dl> + +<h4 id="An_example_that_doesnt_use_the_constraint_validation_API">An example that doesn't use the constraint validation API</h4> + +<p>In order to illustrate this, let's rebuild the previous example so that it works with legacy browsers:</p> + +<pre class="brush: html notranslate"><form> + <p> + <label for="mail"> + <span>Please enter an email address:</span> + <input type="text" class="mail" id="mail" name="mail"> + <span class="error" aria-live="polite"></span> + </label> + <p> + <!-- Some legacy browsers need to have the `type` attribute + explicitly set to `submit` on the `button`element --> + <button type="submit">Submit</button> +</form></pre> + +<p>As you can see, the HTML is almost the same; we just removed the HTML validation features. Note that <a href="/en-US/docs/Accessibility/ARIA">ARIA</a> is an independent specification that's not specifically related to HTML5.</p> + +<h5 id="CSS_2">CSS</h5> + +<p>Similarly, the CSS doesn't need to change very much; we just turn the {{cssxref(":invalid")}} CSS pseudo-class into a real class and avoid using the attribute selector that does not work on Internet Explorer 6.</p> + +<pre class="brush: css notranslate">/* This is just to make the example nicer */ +body { + font: 1em sans-serif; + padding: 0; + margin : 0; +} + +form { + max-width: 200px; +} + +p * { + display: block; +} + +input.mail { + -webkit-appearance: none; + + width: 100%; + border: 1px solid #333; + margin: 0; + + font-family: inherit; + font-size: 90%; + + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +/* This is our style for the invalid fields */ +input.invalid{ + border-color: #900; + background-color: #FDD; +} + +input:focus.invalid { + outline: none; +} + +/* This is the style of our error messages */ +.error { + width : 100%; + padding: 0; + + font-size: 80%; + color: white; + background-color: #900; + border-radius: 0 0 5px 5px; + + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.error.active { + padding: 0.3em; +}</pre> + +<h5 id="JavaScript_2">JavaScript</h5> + +<p>The big changes are in the JavaScript code, which needs to do much more of the heavy lifting.</p> + +<pre class="brush: js notranslate">// There are fewer ways to pick a DOM node with legacy browsers +var form = document.getElementsByTagName('form')[0]; +var email = document.getElementById('mail'); + +// The following is a trick to reach the next sibling Element node in the DOM +// This is dangerous because you can easily build an infinite loop. +// In modern browsers, you should prefer using element.nextElementSibling +var error = email; +while ((error = error.nextSibling).nodeType != 1); + +// As per the HTML5 Specification +var emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; + +// Many legacy browsers do not support the addEventListener method. +// Here is a simple way to handle this; it's far from the only one. +function addEvent(element, event, callback) { + var previousEventCallBack = element["on"+event]; + element["on"+event] = function (e) { + var output = callback(e); + + // A callback that returns `false` stops the callback chain + // and interrupts the execution of the event callback. + if (output === false) return false; + + if (typeof previousEventCallBack === 'function') { + output = previousEventCallBack(e); + if(output === false) return false; + } + } +}; + +// Now we can rebuild our validation constraint +// Because we do not rely on CSS pseudo-class, we have to +// explicitly set the valid/invalid class on our email field +addEvent(window, "load", function () { + // Here, we test if the field is empty (remember, the field is not required) + // If it is not, we check if its content is a well-formed e-mail address. + var test = email.value.length === 0 || emailRegExp.test(email.value); + + email.className = test ? "valid" : "invalid"; +}); + +// This defines what happens when the user types in the field +addEvent(email, "input", function () { + var test = email.value.length === 0 || emailRegExp.test(email.value); + if (test) { + email.className = "valid"; + error.innerHTML = ""; + error.className = "error"; + } else { + email.className = "invalid"; + } +}); + +// This defines what happens when the user tries to submit the data +addEvent(form, "submit", function () { + var test = email.value.length === 0 || emailRegExp.test(email.value); + + if (!test) { + email.className = "invalid"; + error.innerHTML = "I expect an e-mail, darling!"; + error.className = "error active"; + + // Some legacy browsers do not support the event.preventDefault() method + return false; + } else { + email.className = "valid"; + error.innerHTML = ""; + error.className = "error"; + } +});</pre> + +<p>The result looks like this:</p> + +<p>{{EmbedLiveSample("An_example_that_doesn't_use_the_constraint_validation_API", "100%", 130)}}</p> + +<p>As you can see, it's not that hard to build a validation system on your own. The difficult part is to make it generic enough to use it both cross-platform and on any form you might create. There are many libraries available to perform form validation; you shouldn't hesitate to use them. Here are a few examples:</p> + +<ul> + <li>Standalone library + <ul> + <li><a href="http://rickharrison.github.com/validate.js/" rel="external">Validate.js</a></li> + </ul> + </li> + <li>jQuery plug-in: + <ul> + <li><a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="external">Validation</a></li> + </ul> + </li> +</ul> + +<h4 id="Remote_validation">Remote validation</h4> + +<p>In some cases, it can be useful to perform some remote validation. This kind of validation is necessary when the data entered by the user is tied to additional data stored on the server side of your application. One use case for this is registration forms, where you ask for a username. To avoid duplication, it's smarter to perform an AJAX request to check the availability of the username rather than asking the user to send the data, then send back the form with an error.</p> + +<p>Performing such a validation requires taking a few precautions:</p> + +<ul> + <li>It requires exposing an API and some data publicly; be sure it is not sensitive data.</li> + <li>Network lag requires performing asynchronous validation. This requires some UI work in order to be sure that the user will not be blocked if the validation is not performed properly.</li> +</ul> + +<h2 id="Conclusion">Conclusion</h2> + +<p>Form validation does not require complex JavaScript, but it does require thinking carefully about the user. Always remember to help your user to correct the data they provide. To that end, be sure to:</p> + +<ul> + <li>Display explicit error messages.</li> + <li>Be permissive about the input format.</li> + <li>Point out exactly where the error occurs (especially on large forms).</li> +</ul> + +<p>{{PreviousMenuNext("Learn/HTML/Forms/Sending_and_retrieving_form_data", "Learn/HTML/Forms/How_to_build_custom_form_widgets", "Learn/HTML/Forms")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form">Your first HTML form</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form">How to structure an HTML form</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/The_native_form_widgets">The native form widgets</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data">Sending form data</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Form_validation">Form data validation</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/How_to_build_custom_form_widgets">How to build custom form widgets</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript">Sending forms through JavaScript</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/HTML_forms_in_legacy_browsers">HTML forms in legacy browsers</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Styling_HTML_forms">Styling HTML forms</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Advanced_styling_for_HTML_forms">Advanced styling for HTML forms</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Property_compatibility_table_for_form_widgets">Property compatibility table for form widgets</a></li> +</ul> diff --git a/files/pt-br/learn/forms/how_to_build_custom_form_controls/index.html b/files/pt-br/learn/forms/how_to_build_custom_form_controls/index.html new file mode 100644 index 0000000000..76e202e685 --- /dev/null +++ b/files/pt-br/learn/forms/how_to_build_custom_form_controls/index.html @@ -0,0 +1,786 @@ +--- +title: How to build custom form widgets +slug: Web/Guide/HTML/Forms/How_to_build_custom_form_widgets +translation_of: Learn/Forms/How_to_build_custom_form_controls +--- +<div>{{LearnSidebar}}{{PreviousMenuNext("Learn/HTML/Forms/Form_validation", "Learn/HTML/Forms/Sending_forms_through_JavaScript", "Learn/HTML/Forms")}}</div> + +<p class="summary">There are many cases where <a href="/en-US/docs/HTML/Forms/The_native_form_widgets" title="/en-US/docs/HTML/Forms/The_native_form_widgets">available HTML form widgets</a> are just nThere are many cases where available HTML form widgets are just not enough. If you want to <a href="/en-US/docs/Advanced_styling_for_HTML_forms" title="/en-US/docs/Advanced_styling_for_HTML_forms">perform advanced styling</a> on some widgets such as the {{HTMLElement("select")}} element or if you want to provide custom behaviors, you have no choice but to build your own widgets.</p> + +<p>In this article, we will see how to build such a widget. To that end, we will work with an example: rebuilding the {{HTMLElement("select")}} element.</p> + +<div class="note"> +<p><strong>Note:</strong> We'll focus on building the widgets, not on how to make the code generic and reusable; that would involve some non-trival JavaScript code and DOM manipulation in an unknown context, and that is out of the scope of this article.</p> +</div> + +<h2 id="Design_structure_and_semantics">Design, structure, and semantics</h2> + +<p>Before building a custom widget, you should start by figuring out exactly what you want. This will save you some precious time. In particular, it's important to clearly define all the states of your widget. To do this, it's good to start with an existing widget whose states and behavior are well known, so that you can simply mimic those as much as possible.</p> + +<p>In our example, we will rebuild the {{HTMLElement("select")}} element. Here is the result we want to achieve:</p> + +<p><img alt="The three states of a select box" src="/files/4481/custom-select.png" style="height: 135px; width: 366px;"></p> + +<p>This screenshot shows the three main states of our widget: the normal state (on the left); the active state (in the middle) and the open state (on the right).</p> + +<p>In terms of behavior, we want our widget to be usable with a mouse as well as with a keyboard, just like any native widget. Let's start by defining how the widget reaches each state:</p> + +<dl> + <dt>The widget is in its normal state when:</dt> + <dd> + <ul> + <li>the page loads</li> + <li>the widget was active and the user clicks anywhere outside the widget</li> + <li>the widget was active and the user moves the focus to another widget using the keyboard</li> + </ul> + + <div class="note"> + <p><strong>Note:</strong> Moving the focus around the page is usually done through hitting the tab key, but this is not standard everywhere. For example cycling through links on a page is done in Safari by default using the <a href="http://www.456bereastreet.com/archive/200906/enabling_keyboard_navigation_in_mac_os_x_web_browsers/" title="http://www.456bereastreet.com/archive/200906/enabling_keyboard_navigation_in_mac_os_x_web_browsers/">Option+Tab combination</a>.</p> + </div> + </dd> + <dt>The widget is in its active state when:</dt> + <dd> + <ul> + <li>the user clicks on it</li> + <li>the user hits the tab key and it gains focus</li> + <li>the widget was in its open state and the user clicks on the widget.</li> + </ul> + </dd> + <dt>The widget is in its open state when:</dt> + <dd> + <ul> + <li>the widget is in any other state than open and the user clicks on it</li> + </ul> + </dd> +</dl> + +<p>Once we know how to change states, it is important to define how to change the widget's value:</p> + +<dl> + <dt>The value changes when:</dt> + <dd> + <ul> + <li>the user clicks on an option when the widget is in the open state</li> + <li>the user hits the up or down arrow keys when the widget is in its active state</li> + </ul> + </dd> +</dl> + +<p>Finally, let's define how the widget's options will behave:</p> + +<ul> + <li>When the widget is opened, the selected option is highlighted</li> + <li>When the mouse is over an option, the option is highlighted and the previously highlighted option is returned to its normal state</li> +</ul> + +<p>For the purposes of our example, we'll stop with that; however, if you're a careful reader, you'll notice that some behaviors are missing. For example, what do you think will happen if the user hits the tab key while the widget is in its open state? The answer is... nothing. OK, the right behavior seems obvious but the fact is, because it's not defined in our specs, it is very easy to overlook this behavior. This is especially true in a team environment when the people who design the widget's behavior are different from the ones who implement it.</p> + +<p>Another fun example: what will happen if the user hits the up or down arrow keys while the widget is in the open state? This one is a little bit trickier. If you consider that the active state and the open state are completely different, the answer is again "nothing will happen" because we did not define any keyboard interactions for the opened state. On the other hand, if you consider that the active state and the open state overlap a bit, the value may change but the option will definitely not be highlighted accordingly, once again because we did not define any keyboard interactions over options when the widget is in its opened state (we have only defined what should happen when the widget is opened, but nothing after that).</p> + +<p>In our example, the missing specifications are obvious so we will handle them, but it can be a real problem on exotic new widgets, for which nobody has the slightest idea of what the right behavior is. So it's always good to spend time in this design stage, because if you define a behavior poorly, or forget to define one, it will be very hard to redefine it once the users have gotten used to it. If you have doubts, ask for the opinions of others, and if you have the budget for it, do not hesitate to <a href="http://en.wikipedia.org/wiki/Usability_testing" rel="external" title="http://en.wikipedia.org/wiki/Usability_testing">perform user tests</a>. This process is called UX Design. If you want to learn more about this topic, you should check out the following helpful resources:</p> + +<ul> + <li><a href="http://www.uxmatters.com/" rel="external" title="http://www.uxmatters.com/">UXMatters.com</a></li> + <li><a href="http://uxdesign.com/" rel="external" title="http://uxdesign.com/">UXDesign.com</a></li> + <li><a href="http://uxdesign.smashingmagazine.com/" rel="external" title="http://uxdesign.smashingmagazine.com/">The UX Design section of SmashingMagazine</a></li> +</ul> + +<div class="note"> +<p><strong>Note: </strong>Also, in most systems there is a way to open the {{HTMLElement("select")}} element to look at all the available choices (this is the same as clicking the {{HTMLElement("select")}} element with a mouse). This is achieved with Alt+Down arrow under Windows and was not implemented in our example —but it would be easy to do so, as the mechanism has already been implemented for the <code>click</code> event.</p> +</div> + +<h3 id="Defining_the_HTML_structure_and_semantics">Defining the HTML structure and semantics</h3> + +<p>Now that the widget's basic functionality has been decided upon, it's time to start building our widget. The first step is to define its HTML structure and to give it some basic semantics. Here is what we need to rebuild a {{HTMLElement("select")}} element:</p> + +<pre class="brush: html"><!-- This is our main container for our widget. + The tabindex attribute is what allows the user to focus the widget. + We'll see later that it's better to set it through JavaScript. --> +<div class="select" tabindex="0"> + + <!-- This container will be used to display the current value of the widget --> + <span class="value">Cherry</span> + + <!-- This container will contain all the options available for our widget. + Because it's a list, it makes sense to use the ul element. --> + <ul class="optList"> + <!-- Each option only contains the value to be displayed, we'll see later + how to handle the real value that will be sent with the form data --> + <li class="option">Cherry</li> + <li class="option">Lemon</li> + <li class="option">Banana</li> + <li class="option">Strawberry</li> + <li class="option">Apple</li> + </ul> + +</div></pre> + +<p>Note the use of class names; these identify each relevant part regardless of the actual underlying HTML elements used. This is important to make sure that we will not bind our CSS and JavaScript to a strong HTML structure, so that we can make implementation changes later without breaking code that uses the widget. For example if you wish to implement the equivalent of the {{HTMLElement("optgroup")}} element.</p> + +<h3 id="Creating_the_look_and_feel_using_CSS">Creating the look and feel using CSS</h3> + +<p>Now that we have a structure, we can start designing our widget. The whole point of building this custom widget is to be able to style this widget exactly as we want. To that end, we will split our CSS work into two parts: the first part will be the CSS rules absolutely necessary to have our widget behave like a {{HTMLElement("select")}} element, and the second part will consist of the fancy styles used to make it look the way we want.</p> + +<h4 id="Required_styles">Required styles</h4> + +<p>The required styles are those necessary to handle the three states of our widget.</p> + +<pre class="brush: css">.select { + /* This will create a positioning context for the list of options */ + position: relative; + + /* This will make our widget become part of the text flow and sizable at the same time */ + display : inline-block; +}</pre> + +<p>We need an extra class <code>active</code> to define the look and feel of our widget when it is in its active state. Because our widget is focusable, we double this custom style with the {{cssxref(":focus")}} pseudo-class in order to be sure they will behave the same.</p> + +<pre class="brush: css">.select .active, +.select:focus { + outline: none; + + /* This box-shadow property is not exactly required, however it's so important to be sure + the active state is visible that we use it as a default value, feel free to override it. */ + box-shadow: 0 0 3px 1px #227755; +}</pre> + +<p>Now, let's handle the list of options:</p> + +<pre class="brush: css">/* The .select selector here is syntactic sugar to be sure the classes we define are + the ones inside our widget. */ +.select .optList { + /* This will make sure our list of options will be displayed below the value + and out of the HTML flow */ + position : absolute; + top : 100%; + left : 0; +}</pre> + +<p>We need an extra class to handle when the list of options is hidden. This is necessary in order to manage the differences between the active state and the open state that do not exactly match.</p> + +<pre class="brush: css">.select .optList.hidden { + /* This is a simple way to hide the list in an accessible way, + we will talk more about accessibility in the end */ + max-height: 0; + visibility: hidden; +}</pre> + +<h4 id="Beautification">Beautification</h4> + +<p>So now that we have the basic functionality in place, the fun can start. The following is just an example of what is possible, and will match the screenshot at the beginning of this article. However, you should feel free to experiment and see what you can come up with.</p> + +<pre class="brush: css">.select { + /* All sizes will be expressed with the em value for accessibility reasons + (to make sure the widget remains resizable if the user uses the + browser's zoom in a text-only mode). The computations are made + assuming 1em == 16px which is the default value in most browsers. + If you are lost with px to em conversion, try http://riddle.pl/emcalc/ */ + font-size : 0.625em; /* this (10px) is the new font size context for em value in this context */ + font-family : Verdana, Arial, sans-serif; + + -moz-box-sizing : border-box; + box-sizing : border-box; + + /* We need extra room for the down arrow we will add */ + padding : .1em 2.5em .2em .5em; /* 1px 25px 2px 5px */ + width : 10em; /* 100px */ + + border : .2em solid #000; /* 2px */ + border-radius : .4em; /* 4px */ + box-shadow : 0 .1em .2em rgba(0,0,0,.45); /* 0 1px 2px */ + + /* The first declaration is for browsers that do not support linear gradients. + The second declaration is because WebKit based browsers haven't unprefixed it yet. + If you want to support legacy browsers, try http://www.colorzilla.com/gradient-editor/ */ + background : #F0F0F0; + background : -webkit-linear-gradient(90deg, #E3E3E3, #fcfcfc 50%, #f0f0f0); + background : linear-gradient(0deg, #E3E3E3, #fcfcfc 50%, #f0f0f0); +} + +.select .value { + /* Because the value can be wider than our widget, we have to make sure it will not + change the widget's width */ + display : inline-block; + width : 100%; + overflow : hidden; + + vertical-align: top; + + /* And if the content overflows, it's better to have a nice ellipsis. */ + white-space : nowrap; + text-overflow: ellipsis; +}</pre> + +<p>We don't need an extra element to design the down arrow; instead, we're using the {{cssxref(":after")}} pseudo-element. However, it could also be implemented using a simple background image on the <code>select</code> class.</p> + +<pre class="brush: css">.select:after { + content : "▼"; /* We use the unicode caracter U+25BC; see http://www.utf8-chartable.de */ + position: absolute; + z-index : 1; /* This will be important to keep the arrow from overlapping the list of options */ + top : 0; + right : 0; + + -moz-box-sizing : border-box; + box-sizing : border-box; + + height : 100%; + width : 2em; /* 20px */ + padding-top : .1em; /* 1px */ + + border-left : .2em solid #000; /* 2px */ + border-radius: 0 .1em .1em 0; /* 0 1px 1px 0 */ + + background-color : #000; + color : #FFF; + text-align : center; +}</pre> + +<p>Next, let's style the list of options:</p> + +<pre class="brush: css">.select .optList { + z-index : 2; /* We explicitly said the list of options will always overlap the down arrow */ + + /* this will reset the default style of the ul element */ + list-style: none; + margin : 0; + padding: 0; + + -moz-box-sizing : border-box; + box-sizing : border-box; + + /* This will ensure that even if the values are smaller than the widget, + the list of options will be as large as the widget itself */ + min-width : 100%; + + /* In case the list is too long, its content will overflow vertically + (which will add a vertical scrollbar automatically) but never horizontally + (because we haven't set a width, the list will adjust its width automatically. + If it can't, the content will be truncated) */ + max-height: 10em; /* 100px */ + overflow-y: auto; + overflow-x: hidden; + + border: .2em solid #000; /* 2px */ + border-top-width : .1em; /* 1px */ + border-radius: 0 0 .4em .4em; /* 0 0 4px 4px */ + + box-shadow: 0 .2em .4em rgba(0,0,0,.4); /* 0 2px 4px */ + background: #f0f0f0; +}</pre> + +<p>For the options, we need to add a <code>highlight</code> class to be able to identify the value the user will pick (or has picked).</p> + +<pre class="brush: css">.select .option { + padding: .2em .3em; /* 2px 3px */ +} + +.select .highlight { + background: #000; + color: #FFFFFF; +}</pre> + +<p>So here's the result with our three states:</p> + +<table> + <thead> + <tr> + <th scope="col" style="text-align: center;">Basic state</th> + <th scope="col" style="text-align: center;">Active state</th> + <th scope="col" style="text-align: center;">Open state</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{EmbedLiveSample("Basic_state",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_1")}}</td> + <td>{{EmbedLiveSample("Active_state",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_1")}}</td> + <td>{{EmbedLiveSample("Open_state",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_1")}}</td> + </tr> + <tr> + <td colspan="3" style="text-align: center;"><a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_1" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_1">Check out the source code</a></td> + </tr> + </tbody> +</table> + +<h2 id="Bring_your_widget_to_life_with_JavaScript">Bring your widget to life with JavaScript</h2> + +<p>Now that our design and structure are ready, we can write the JavaScript code to make the widget actually work.</p> + +<div class="warning"> +<p><strong>Warning:</strong> The following code is educational and should not be used as-is. Among many things, as we'll see, it is not future-proof and it will not work on legacy browsers. It also has redundant parts that should be optimized in production code.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Creating reusable widgets is something that can be a bit tricky. The <a href="http://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html" rel="external" title="http://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html">W3C Web Component draft</a> is one of the answers to this specific issue. <a href="http://x-tags.org/" rel="external" title="http://x-tags.org/">The X-Tag project</a> is a test implementation of this specification; we encourage you to take a look at it.</p> +</div> + +<h3 id="Why_isn't_it_working">Why isn't it working?</h3> + +<p>Before we start, it's important to remember something very important about JavaScript: inside a browser, <strong>it's an unreliable technology</strong>. When you are building custom widgets, you'll have to rely on JavaScript because it's a necessary thread to tie everything together. However, there are many cases in which JavaScript isn't able to run in the browser:</p> + +<ul> + <li>The user has turned off JavaScript: This is the most unusual case ever; very few people turn off JavaScript nowadays.</li> + <li>The script is not loading. This is one of the most common cases, especially in the mobile world where the network is not very reliable.</li> + <li>The script is buggy. You should always consider this possibility.</li> + <li>The script is in conflict with a third party script. This can happen with tracking scripts or any bookmarklets the user uses.</li> + <li>The script is in conflict with, or is affected by, a browser extension (such as Firefox's <a href="https://addons.mozilla.org/fr/firefox/addon/noscript/" rel="external" title="https://addons.mozilla.org/fr/firefox/addon/noscript/">NoScript</a> extension or Chrome's <a href="https://chrome.google.com/webstore/detail/notscripts/odjhifogjcknibkahlpidmdajjpkkcfn" rel="external" title="https://chrome.google.com/webstore/detail/notscripts/odjhifogjcknibkahlpidmdajjpkkcfn">NotScripts</a> extension).</li> + <li>The user is using a legacy browser, and one of the features you require is not supported. This will happen frequently when you make use of cutting-edge APIs.</li> +</ul> + +<p>Because of these risks, it's really important to seriously consider what will happen if JavaScript isn't working. Dealing in detail with this issue is out of the scope of this article because it's closely linked to how you want to make your script generic and reusable, but we'll consider the basics of this in our example.</p> + +<p>In our example, if our JavaScript code isn't running, we'll fall back to displaying a standard {{HTMLElement("select")}} element. To achieve this, we need two things.</p> + +<p>First, we need to add a regular {{HTMLElement("select")}} element before each use of our custom widget. This is actually also required in order to be able to send data from our custom widget along with the rest of our form data; more about this later.</p> + +<pre class="brush: html"><body class="no-widget"> + <form> + <select name="myFruit"> + <option>Cherry</option> + <option>Lemon</option> + <option>Banana</option> + <option>Strawberry</option> + <option>Apple</option> + </select> + + <div class="select"> + <span class="value">Cherry</span> + <ul class="optList hidden"> + <li class="option">Cherry</li> + <li class="option">Lemon</li> + <li class="option">Banana</li> + <li class="option">Strawberry</li> + <li class="option">Apple</li> + </ul> + </div> + </form> + +</body></pre> + +<p>Second, we need two new classes to let us hide the unneeded element (that is, the "real" {{HTMLElement("select")}} element if our script isn't running, or the custom widget if it is running). Note that by default, our HTML code hides our custom widget.</p> + +<pre class="brush: css">.widget select, +.no-widget .select { + /* This CSS selector basically says: + - either we have set the body class to "widget" and thus we hide the actual {{HTMLElement("select")}} element + - or we have not changed the body class, therefore the body class is still "no-widget", + so the elements whose class is "select" must be hidden */ + position : absolute; + left : -5000em; + height : 0; + overflow : hidden; +}</pre> + +<p>Now we just need a JavaScript switch to determine if the script is running or not. This switch is very simple: if at page load time our script is running, it will remove the <code>no-widget</code> class and add the <code>widget</code> class, thereby swapping the visibility of the {{HTMLElement("select")}} element and of the custom widget.</p> + +<pre class="brush: js">window.addEventListener("load", function () { + document.body.classList.remove("no-widget"); + document.body.classList.add("widget"); +});</pre> + +<table> + <thead> + <tr> + <th scope="col" style="text-align: center;">Without JS</th> + <th scope="col" style="text-align: center;">With JS</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{EmbedLiveSample("No_JS",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_2")}}</td> + <td>{{EmbedLiveSample("JS",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_2")}}</td> + </tr> + <tr> + <td colspan="2" style="text-align: center;"><a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_2" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_2">Check out the source code</a></td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Note:</strong> If you really want to make your code generic and reusable, instead of doing a class switch it's far better to just add the widget class to hide the {{HTMLElement("select")}} elements, and to dynamically add the DOM tree representing the custom widget after every {{HTMLElement("select")}} element in the page.</p> +</div> + +<h3 id="Making_the_job_easier">Making the job easier</h3> + +<p>In the code we are about to build, we will use the standard DOM API to do all the work we need. However, although DOM API support has gotten much better in browsers, there are always issues with legacy browsers (especially with good old Internet Explorer).</p> + +<p>If you want to avoid trouble with legacy browsers, there are two ways to do so: using a dedicated framework such as <a href="http://jquery.com/" rel="external" title="http://jquery.com/">jQuery</a>, <a href="https://github.com/julienw/dollardom" rel="external" title="https://github.com/julienw/dollardom">$dom</a>, <a href="http://prototypejs.org/" rel="external" title="http://prototypejs.org/">prototype</a>, <a href="http://dojotoolkit.org/" rel="external" title="http://dojotoolkit.org/">Dojo</a>, <a href="http://yuilibrary.com/" rel="external" title="http://yuilibrary.com/">YUI</a>, or the like, or by polyfilling the missing feature you want to use (which can easily be done through conditional loading, with the <a href="http://yepnopejs.com/" rel="external" title="http://yepnopejs.com/">yepnope</a> library for example).</p> + +<p>The features we plan to use are the following (ordered from the riskiest to the safest):</p> + +<ol> + <li>{{domxref("element.classList","classList")}}</li> + <li>{{domxref("EventTarget.addEventListener","addEventListener")}}</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach">forEach</a></code> (This is not DOM but modern JavaScript)</li> + <li>{{domxref("element.querySelector","querySelector")}} and {{domxref("element.querySelectorAll","querySelectorAll")}}</li> +</ol> + +<p>Beyond the availability of those specific features, there is still one issue remaining before starting. The object returned by the {{domxref("element.querySelectorAll","querySelectorAll()")}} function is a {{domxref("NodeList")}} rather than an <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array">Array</a></code>. This is important because <code>Array</code> objects support the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach">forEach</a></code> function, but {{domxref("NodeList")}} doesn't. Because {{domxref("NodeList")}} really looks like an <code>Array</code> and because <code>forEach</code> is so convenient to use, we can easily add the support of <code>forEach</code> to {{domxref("NodeList")}} in order to make our life easier, like so:</p> + +<pre class="brush: js">NodeList.prototype.forEach = function (callback) { + Array.prototype.forEach.call(this, callback); +}</pre> + +<p>We weren't kidding when we said it's easy to do.</p> + +<h3 id="Building_event_callbacks">Building event callbacks</h3> + +<p>The ground is ready, we can now start to define all the functions that will be used each time the user interacts with our widget.</p> + +<pre class="brush: js">// This function will be used each time we want to deactivate a custom widget +// It takes one parameter +// select : the DOM node with the `select` class to deactivate +function deactivateSelect(select) { + + // If the widget is not active there is nothing to do + if (!select.classList.contains('active')) return; + + // We need to get the list of options for the custom widget + var optList = select.querySelector('.optList'); + + // We close the list of option + optList.classList.add('hidden'); + + // and we deactivate the custom widget itself + select.classList.remove('active'); +} + +// This function will be used each time the user wants to (de)activate the widget +// It takes two parameters: +// select : the DOM node with the `select` class to activate +// selectList : the list of all the DOM nodes with the `select` class +function activeSelect(select, selectList) { + + // If the widget is already active there is nothing to do + if (select.classList.contains('active')) return; + + // We have to turn off the active state on all custom widgets + // Because the deactivateSelect function fulfill all the requirement of the + // forEach callback function, we use it directly without using an intermediate + // anonymous function. + selectList.forEach(deactivateSelect); + + // And we turn on the active state for this specific widget + select.classList.add('active'); +} + +// This function will be used each time the user wants to open/closed the list of options +// It takes one parameter: +// select : the DOM node with the list to toggle +function toggleOptList(select) { + + // The list is kept from the widget + var optList = select.querySelector('.optList'); + + // We change the class of the list to show/hide it + optList.classList.toggle('hidden'); +} + +// This function will be used each time we need to highlight an option +// It takes two parameters: +// select : the DOM node with the `select` class containing the option to highlight +// option : the DOM node with the `option` class to highlight +function highlightOption(select, option) { + + // We get the list of all option available for our custom select element + var optionList = select.querySelectorAll('.option'); + + // We remove the highlight from all options + optionList.forEach(function (other) { + other.classList.remove('highlight'); + }); + + // We highlight the right option + option.classList.add('highlight'); +};</pre> + +<p>That's all you need in order to handle the various states of the custom widget.</p> + +<p>Next, we bind these functions to the appropriate events:</p> + +<pre class="brush: js">// We handle the event binding when the document is loaded. +window.addEventListener('load', function () { + var selectList = document.querySelectorAll('.select'); + + // Each custom widget needs to be initialized + selectList.forEach(function (select) { + + // as well as all its `option` elements + var optionList = select.querySelectorAll('.option'); + + // Each time a user hovers their mouse over an option, we highlight the given option + optionList.forEach(function (option) { + option.addEventListener('mouseover', function () { + // Note: the `select` and `option` variable are closures + // available in the scope of our function call. + highlightOption(select, option); + }); + }); + + // Each times the user click on a custom select element + select.addEventListener('click', function (event) { + // Note: the `select` variable is a closure + // available in the scope of our function call. + + // We toggle the visibility of the list of options + toggleOptList(select); + }); + + // In case the widget gain focus + // The widget gains the focus each time the user clicks on it or each time + // they use the tabulation key to access the widget + select.addEventListener('focus', function (event) { + // Note: the `select` and `selectList` variable are closures + // available in the scope of our function call. + + // We activate the widget + activeSelect(select, selectList); + }); + + // In case the widget loose focus + select.addEventListener('blur', function (event) { + // Note: the `select` variable is a closure + // available in the scope of our function call. + + // We deactivate the widget + deactivateSelect(select); + }); + }); +});</pre> + +<p>At that point, our widget will change state according to our design, but its value doesn't get updated yet. We'll handle that next.</p> + +<table> + <thead> + <tr> + <th scope="col" style="text-align: center;">Live example</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{EmbedLiveSample("Change_states",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_3")}}</td> + </tr> + <tr> + <td style="text-align: center;"><a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_3" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_3">Check out the source code</a></td> + </tr> + </tbody> +</table> + +<h3 id="Handling_the_widget's_value">Handling the widget's value</h3> + +<p>Now that our widget is working, we have to add code to update its value according to user input and make it possible to send the value along with form data.</p> + +<p>The easiest way to do this is to use a native widget under the hood. Such a widget will keep track of the value with all the built-in controls provided by the browser, and the value will be sent as usual when a form is submitted. There's no point in reinventing the wheel when we can have all this done for us.</p> + +<p>As seen previously, we already use a native select widget as a fallback for accessibility reasons; we can simply synchronize its value with that of our custom widget:</p> + +<pre class="brush: js">// This function updates the displayed value and synchronizes it with the native widget. +// It takes two parameters: +// select : the DOM node with the class `select` containing the value to update +// index : the index of the value to be selected +function updateValue(select, index) { + // We need to get the native widget for the given custom widget + // In our example, that native widget is a sibling of the custom widget + var nativeWidget = select.previousElementSibling; + + // We also need to get the value placeholder of our custom widget + var value = select.querySelector('.value'); + + // And we need the whole list of options + var optionList = select.querySelectorAll('.option'); + + // We set the selected index to the index of our choice + nativeWidget.selectedIndex = index; + + // We update the value placeholder accordingly + value.innerHTML = optionList[index].innerHTML; + + // And we highlight the corresponding option of our custom widget + highlightOption(select, optionList[index]); +}; + +// This function returns the current selected index in the native widget +// It takes one parameter: +// select : the DOM node with the class `select` related to the native widget +function getIndex(select) { + // We need to access the native widget for the given custom widget + // In our example, that native widget is a sibling of the custom widget + var nativeWidget = select.previousElementSibling; + + return nativeWidget.selectedIndex; +};</pre> + +<p>With these two functions, we can bind the native widgets to the custom ones:</p> + +<pre class="brush: js">// We handle event binding when the document is loaded. +window.addEventListener('load', function () { + var selectList = document.querySelectorAll('.select'); + + // Each custom widget needs to be initialized + selectList.forEach(function (select) { + var optionList = select.querySelectorAll('.option'), + selectedIndex = getIndex(select); + + // We make our custom widget focusable + select.tabIndex = 0; + + // We make the native widget no longer focusable + select.previousElementSibling.tabIndex = -1; + + // We make sure that the default selected value is correctly displayed + updateValue(select, selectedIndex); + + // Each time a user clicks on an option, we update the value accordingly + optionList.forEach(function (option, index) { + option.addEventListener('click', function (event) { + updateValue(select, index); + }); + }); + + // Each time a user uses their keyboard on a focused widget, we update the value accordingly + select.addEventListener('keyup', function (event) { + var length = optionList.length, + index = getIndex(select); + + // When the user hits the down arrow, we jump to the next option + if (event.keyCode === 40 && index < length - 1) { index++; } + + // When the user hits the up arrow, we jump to the previous option + if (event.keyCode === 38 && index > 0) { index--; } + + updateValue(select, index); + }); + }); +});</pre> + +<p>In the code above, it's worth noting the use of the <code><a href="/en-US/docs/Web/API/HTMLElement/tabIndex" title="/en-US/docs/Web/API/HTMLElement/tabIndex">tabIndex</a></code> property. Using this property is necessary to ensure that the native widget will never gain focus, and to make sure that our custom widget gains focus when the user uses his keyboard or his mouse.</p> + +<p>With that, we're done! Here's the result:</p> + +<table> + <thead> + <tr> + <th scope="col" style="text-align: center;">Live example</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{EmbedLiveSample("Change_states",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_4")}}</td> + </tr> + <tr> + <td style="text-align: center;"><a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_4" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_4">Check out the source code</a></td> + </tr> + </tbody> +</table> + +<p>But wait a second, are we really done?</p> + +<h2 id="Make_it_accessible">Make it accessible</h2> + +<p>We have built something that works and though we're far from a fully-featured select box, it works nicely. But what we've done is nothing more than fiddle with the DOM. It has no real semantics, and even though it looks like a select box, from the browser's point of view it isn't one, so assistive technologies won't be able to understand it's a select box. In short, this pretty new select box isn't accessible!</p> + +<p>Fortunately, there is a solution and it's called <a href="/en-US/docs/Accessibility/ARIA" title="/en-US/docs/Accessibility/ARIA">ARIA</a>. ARIA stands for "Accessible Rich Internet Application", and it's <a href="http://www.w3.org/TR/wai-aria/" rel="external" title="http://www.w3.org/TR/wai-aria/">a W3C specification</a> specifically designed for what we are doing here: making web applications and custom widgets accessible. It's basically a set of attributes that extend HTML so that we can better describe roles, states and properties as though the element we've just devised was the native element it tries to pass for. Using these attributes is dead simple, so let's do it.</p> + +<h3 id="The_role_attribute">The <code>role</code> attribute</h3> + +<p>The key attribute used by <a href="/en-US/docs/Accessibility/ARIA" title="/en-US/docs/Accessibility/ARIA">ARIA</a> is the <a href="/en-US/docs/Accessibility/ARIA/ARIA_Techniques" title="/en-US/docs/Accessibility/ARIA/ARIA_Techniques"><code>role</code></a> attribute. The <a href="/en-US/docs/Accessibility/ARIA/ARIA_Techniques" title="/en-US/docs/Accessibility/ARIA/ARIA_Techniques"><code>role</code></a> attribute accepts a value that defines what an element is used for. Each role defines its own requirements and behaviors. In our example, we will use the <code><a href="/en-US/docs/Accessibility/ARIA/ARIA_Techniques/Using_the_listbox_role" title="/en-US/docs/Accessibility/ARIA/ARIA_Techniques/Using_the_listbox_role">listbox</a></code> role. It's a "composite role", which means elements with that role expect to have children, each with a specific role (in this case, at least one child with the <code>option</code> role).</p> + +<p>It's also worth noting that ARIA defines roles that are applied by default to standard HTML markup. For example, the {{HTMLElement("table")}} element matches the role <code>grid</code>, and the {{HTMLElement("ul")}} element matches the role <code>list</code>. Because we use a {{HTMLElement("ul")}} element, we want to make sure the <code>listbox</code> role of our widget will supersede the <code>list</code> role of the {{HTMLElement("ul")}} element. To that end, we will use the role <code>presentation</code>. This role is designed to let us indicate that an element has no special meaning, and is used solely to present information. We will apply it to our {{HTMLElement("ul")}} element.</p> + +<p>To support the <code><a href="/en-US/docs/Accessibility/ARIA/ARIA_Techniques/Using_the_listbox_role" title="/en-US/docs/Accessibility/ARIA/ARIA_Techniques/Using_the_listbox_role">listbox</a></code> role, we just have to update our HTML like this:</p> + +<pre class="brush: html"><!-- We add the role="listbox" attribute to our top element --> +<div class="select" role="listbox"> + <span class="value">Cherry</span> + <!-- We also add the role="presentation" to the ul element --> + <ul class="optList" role="presentation"> + <!-- And we add the role="option" attribute to all the li elements --> + <li role="option" class="option">Cherry</li> + <li role="option" class="option">Lemon</li> + <li role="option" class="option">Banana</li> + <li role="option" class="option">Strawberry</li> + <li role="option" class="option">Apple</li> + </ul> +</div></pre> + +<div class="note"> +<p><strong>Note:</strong> Including both the <code>role</code> attribute and a <code>class</code> attribute is only necessary if you want to support legacy browsers that do not support the <a href="/en-US/docs/CSS/Attribute_selectors" title="/en-US/docs/CSS/Attribute_selectors">CSS attribute selectors</a>.</p> +</div> + +<h3 id="The_aria-selected_attribute">The <code>aria-selected</code> attribute</h3> + +<p>Using the <a href="/en-US/docs/Accessibility/ARIA/ARIA_Techniques" title="/en-US/docs/Accessibility/ARIA/ARIA_Techniques"><code>role</code></a> attribute is not enough. <a href="/en-US/docs/Accessibility/ARIA" title="/en-US/docs/Accessibility/ARIA">ARIA</a> also provides many states and property attributes. The more and better you use them, the better your widget will be understood by assistive technologies. In our case, we will limit our usage to one attribute: <code>aria-selected</code>.</p> + +<p>The <code>aria-selected</code> attribute is used to mark which option is currently selected; this lets assistive technologies inform the user what the current selection is. We will use it dynamically with JavaScript to mark the selected option each time the user chooses one. To that end, we need to revise our <code>updateValue()</code> function:</p> + +<pre class="brush: js">function updateValue(select, index) { + var nativeWidget = select.previousElementSibling; + var value = select.querySelector('.value'); + var optionList = select.querySelectorAll('.option'); + + // We make sure that all the options are not selected + optionList.forEach(function (other) { + other.setAttribute('aria-selected', 'false'); + }); + + // We make sure the chosen option is selected + optionList[index].setAttribute('aria-selected', 'true'); + + nativeWidget.selectedIndex = index; + value.innerHTML = optionList[index].innerHTML; + highlightOption(select, optionList[index]); +};</pre> + +<p>Here is the final result of all these changes (you'll get a better feel for this by trying it with an assistive technology such as <a href="http://www.nvda-project.org/" rel="external" title="http://www.nvda-project.org/">NVDA</a> or <a href="http://www.apple.com/accessibility/voiceover/" rel="external" title="http://www.apple.com/accessibility/voiceover/">VoiceOver</a>):</p> + +<table> + <thead> + <tr> + <th scope="col" style="text-align: center;">Live example</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{EmbedLiveSample("Change_states",120,130, "", "HTML/Forms/How_to_build_custom_form_widgets/Example_5")}}</td> + </tr> + <tr> + <td style="text-align: center;"><a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_5" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets/Example_2">Check out the final source code</a></td> + </tr> + </tbody> +</table> + +<h2 id="Conclusion">Conclusion</h2> + +<p>We have seen all the basics of building a custom form widget, but as you can see it's not trivial to do, and often it's better and easier to rely on third-party libraries instead of coding them from scratch yourself (unless, of course, your goal is to build such a library).</p> + +<p>Here are a few libraries you should consider before coding your own:</p> + +<ul> + <li><a href="http://jqueryui.com/" rel="external" title="http://jqueryui.com/">jQuery UI</a></li> + <li><a href="https://github.com/marghoobsuleman/ms-Dropdown" rel="external" title="https://github.com/marghoobsuleman/ms-Dropdown">msDropDown</a></li> + <li><a href="http://www.emblematiq.com/lab/niceforms/" rel="external" title="http://www.emblematiq.com/lab/niceforms/">Nice Forms</a></li> + <li><a href="https://www.google.fr/search?q=HTML+custom+form+controls&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:fr:official&client=firefox-a" rel="external" title="https://www.google.fr/search?q=HTML+custom+form+controls&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:fr:official&client=firefox-a">And many more…</a></li> +</ul> + +<p>If you want to move forward, the code in this example needs some improvement before it becomes generic and reusable. This is an exercise you can try to perform. Two hints to help you in this: the first argument for all our functions is the same, which means those functions need the same context. Building an object to share that context would be wise. Also, you need to make it feature-proof; that is, it needs to be able to work better with a variety of browsers whose compatibility with the Web standards they use vary. Have fun!</p> + +<p>{{PreviousMenuNext("Learn/HTML/Forms/Form_validation", "Learn/HTML/Forms/Sending_forms_through_JavaScript", "Learn/HTML/Forms")}}</p> + +<p> </p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form">Your first HTML form</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form">How to structure an HTML form</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/The_native_form_widgets">The native form widgets</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data">Sending form data</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Form_validation">Form data validation</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/How_to_build_custom_form_widgets">How to build custom form widgets</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript">Sending forms through JavaScript</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/HTML_forms_in_legacy_browsers">HTML forms in legacy browsers</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Styling_HTML_forms">Styling HTML forms</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Advanced_styling_for_HTML_forms">Advanced styling for HTML forms</a></li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Property_compatibility_table_for_form_widgets">Property compatibility table for form widgets</a></li> +</ul> + +<p> </p> diff --git a/files/pt-br/learn/forms/how_to_structure_a_web_form/index.html b/files/pt-br/learn/forms/how_to_structure_a_web_form/index.html new file mode 100644 index 0000000000..33a562813c --- /dev/null +++ b/files/pt-br/learn/forms/how_to_structure_a_web_form/index.html @@ -0,0 +1,304 @@ +--- +title: Como estruturar um formulário HTML +slug: Web/Guide/HTML/Forms/How_to_structure_an_HTML_form +tags: + - Beginner + - CodingScripting + - Example + - Forms + - Guide + - HTML + - Learn + - Structure + - Web +translation_of: Learn/Forms/How_to_structure_a_web_form +--- +<div> +<p>{{LearnSidebar}}</p> + +<p>{{PreviousMenuNext("Learn/HTML/Forms/Your_first_HTML_form", "Learn/HTML/Forms/The_native_form_widgets", "Learn/HTML/Forms")}}</p> +</div> + +<p class="summary">Com o básico fora do caminho, podemos olhar melhor para os elementos utilizados, a fim de entender as diferentes partes de um formulário.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Pré-Requisitos:</th> + <td>Leitura sobre computação básica e <a href="/docs/Learn/HTML/Introduction_to_HTML">entendimento básico de HTML.</a></td> + </tr> + <tr> + <th scope="row">Objetivo:</th> + <td>Entender como estruturar formulários HTML e entregar a eles semântica de forma a torná-los úteis e acessíveis.</td> + </tr> + </tbody> +</table> + +<p>A flexibilidade dos formulários HTML fazem com que sejam uma das estruturas mais complexas do HTML, você pode construir qualquer tipo básico de formulário usando elementos e atributos exclusivos de formulários. Assim, usar a estrutura correta ao criar um formulário HTML o ajudará a garantir que o formulário seja utilizável e <a href="/pt-BR/docs/Learn/Accessibility">acessível</a>.</p> + +<h2 id="O_elemento_<form>">O elemento <form> </h2> + +<p>O elemento {{HTMLElement("form")}} é o elemento que formalmente define o formulário e os atributos que definem a maneira como esse formulário se comporta. Sempre que você desejar criar um formulário HTML, você deve iniciá-lo usando este elemento, colocando todo o conteúdo dentro deste. Muitas tecnologias assistivas ou plugins de navegadores são capazes de descobrir elemetos {{HTMLElement("form")}} e de implementar ganchos especiais para torná-los mais fáceis de usar.</p> + +<p>Nós já vimos isto em um artigo anterior:</p> + +<div class="note"><strong>Nota:</strong> É estritamente proíbido aninhar um formulário dentro de outro formulário. Isto pode fazer com que os formulários se comportem de maneira imprevisível baseada no navegador que está sendo utilizado.</div> + +<p>Note que, sempre é possível usar um widget de formulário fora de um elemento {{HTMLElement("form")}} mas se o fizer, o widget não terá nada a ver com o formulário. Estes widgets podem ser usados fora de um formulário, mas para tanto você deverá ter um plano especial para eles, pois este não farão nada por si próprios. Você terá de controlar o comportamento deles através de JavaScript.</p> + +<div class="note"> +<p><strong>Nota: </strong>O HTML 5 introduziu o atributo <code>form</code> no grupo de elementos de formulários em HTML. Ele deve deixá-lo atrelar explícitamente um elemento com um form mesmo se não estiver dentro de um {{ HTMLElement("form") }}. Infelizmente, devido ao tempo de vida, essa implementação ainda pelos navegadores ainda não é boa o suficiente para se confiar nela.</p> +</div> + +<h2 id="Os_elementos_<fieldset>_e_<legend>">Os elementos <fieldset> e <legend></h2> + +<p>O elemento {{HTMLElement ("fieldset")}} é uma maneira conveniente de criar grupos de widgets que compartilham o mesmo propósito. Um elemento {{HTMLElement ("fieldset")}} pode ser rotulado com um elemento {{HTMLElement ("legend")}}. O elemento {{HTMLElement ("legend")}} descreve formalmente a finalidade do elemento {{HTMLElement ("fieldset")}} ao qual está incluído.</p> + +<p>Muitas tecnologias assistivas usarão o elemento {{HTMLElement ("legend")}} como se fosse parte da etiqueta de cada widget dentro do elemento {{HTMLElement ("fieldset")}} correspondente. Por exemplo, alguns leitores de tela, como <a href="http://www.freedomscientific.com/products/fs/jaws-product-page.asp">Jaws</a> ou <a href="http://www.nvda-project.org/">NVDA</a>, pronunciarão o conteúdo da legenda antes de pronunciar o rótulo de cada widget.</p> + +<p>Aqui está um pequeno exemplo:</p> + +<pre class="brush:html; notranslate"><form> + <fieldset> + <legend>Fruit juice size</legend> + <p> + <input type="radio" name="size" id="size_1" value="small" /> + <label for="size_1">Small</label> + </p> + <p> + <input type="radio" name="size" id="size_2" value="medium" /> + <label for="size_2">Medium</label> + </p> + <p> + <input type="radio" name="size" id="size_3" value="large" /> + <label for="size_3">Large</label> + </p> + </fieldset> +</form></pre> + +<p>Com este exemplo, um leitor de tela pronunciará "Fruit juice size small" para o primeiro widget, "Fruit juice size medium" para o segundo, e "Fruit juice size large" para o terceiro.</p> + +<p>O caso de uso neste exemplo é um dos mais importantes. Cada vez que você tiver um conjunto de botões de opção, você deve ter certeza de que eles estão aninhados dentro de um elemento {{HTMLElement ("fieldset")}}. Existem outros casos de uso e, em geral, o elemento {{HTMLElement ("fieldset")}} também pode ser usado para conferir acessibilidade a um formulário. Devido à sua influência sobre a tecnologia assistiva, o elemento {{HTMLElement ("fieldset")}} é um dos elementos-chave para a construção de formulários acessíveis. No entanto, é sua responsabilidade não abusá-lo. Se possível, cada vez que você criar um formulário, tente ouvir como o leitor de tela o interpreta. Se parecer estranho, é uma boa sugestão de que sua estrutura de formulário precisa ser melhorada.</p> + +<h2 id="O_elemento_<label>">O elemento <label> </h2> + +<p>Como vimos no artigo anterior, o elemento {{HTMLElement ("label")}} é a maneira formal de definir um rótulo para um widget de formulário HTML. Esse é o elemento mais importante se você quiser criar formulários acessíveis - quando implementados corretamente, os leitores de tela falarão o rótulo de um elemento de formulário juntamente com as instruções relacionadas. Veja este exemplo, que vimos no artigo anterior:</p> + +<pre class="notranslate"><code><label for="name">Name:</label> <input type="text" id="name" name="user_name"></code></pre> + +<p>Com o <label> associado corretamente ao <input> por meio de seus atributos 'for' e 'id' respectivamente (o 'label' do atributo faz referência ao atributo id do widget correspondente), um leitor de tela lerá algo como "Nome, editar texto".</p> + +<p>Se o 'label' não estiver configurado corretamente, um leitor de tela só lerá algo como "Editar texto em branco", o que não é muito útil.</p> + +<p>Observe que um widget pode ser aninhado dentro de seu elemento <label>, assim:</p> + +<pre class="notranslate"><code><label for="name"> + Name: <input type="text" id="name" name="user_name"> +</label></code></pre> + +<p>Mesmo nesses casos, entretanto, é considerada a melhor prática definir o atributo 'for' porque algumas tecnologias assistivas não entendem os relacionamentos implícitos entre labels e widgets.</p> + +<h3 id="Labels_são_clicáveis_também_!.">Labels são clicáveis também !.</h3> + +<p>Outra vantagem de configurar 'labels' adequadamente é que você pode clicar no label para ativar o widget correspondente, em todos os navegadores. Isso é útil para exemplos como entradas de texto, onde você pode clicar no label, bem como na entrada para focalizá-lo, mas é especialmente útil para botões de opção e caixas de seleção - a área de acerto de tal controle pode ser muito pequena, então é útil para torná-lo o maior possível.</p> + +<p>Por exemplo:</p> + +<pre class="notranslate"><code><form> + <p> + <label for="taste_1">I like cherry</label> + <input type="checkbox" id="taste_1" name="taste_cherry" value="1"> + </p> + <p> + <label for="taste_2">I like banana</label> + <input type="checkbox" id="taste_2" name="taste_banana" value="2"> + </p> +</form></code></pre> + +<div class="blockIndicator note"> +<p><strong>Nota: Você pode encontrar este exemplo em</strong> <a href="https://github.com/mdn/learning-area/blob/master/html/forms/html-form-structure/checkbox-label.html">checkbox-label.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/html-form-structure/checkbox-label.html">ver ao vivo também</a>).</p> +</div> + +<h3 id="Múltiplos_labels">Múltiplos labels</h3> + +<p>Estritamente falando, você pode colocar vários rótulos em um único widget, mas isso não é uma boa ideia, pois algumas tecnologias de assistência podem ter problemas para lidar com eles. No caso de vários rótulos, você deve aninhar um widget e seus rótulos dentro de um único elemento {{htmlelement ("label")}}.</p> + +<p>Vamos considerar este exemplo:</p> + +<pre class="notranslate"><code><p>Required fields are followed by <abbr title="required">*</abbr>.</p> + +<!-- So this: --> +<div> + <label for="username">Name:</label> + <input type="text" name="username"> + <label for="username"><abbr title="required">*</abbr></label> +</div> + +<!-- would be better done like this: --> +<div> + <label for="username"> + <span>Name:</span> + <input id="username" type="text" name="username"> + <abbr title="required">*</abbr> + </label> +</div> + +<!-- But this is probably best: --> +<div> + <label for="username">Name: <abbr title="required">*</abbr></label> + <input id="username" type="text" name="username"> +</div></code></pre> + +<p>The paragraph at the top defines the rule for required elements. It must be at the beginning to make sure that assistive technologies such as screen readers will display or vocalize it to the user before they find a required element. That way, they will know what the asterisk means. A screen reader will speak the star as "<em>star</em>" or "<em>required</em>", depending on the screen reader's settings — in any case, what will be spoken is made clear in the first paragraph).</p> + +<ul> + <li>In the first example, the label is not read out at all with the input — you just get "edit text blank", plus the actual labels are read out separately. The multiple <code><label></code>elements confuse the screenreader.</li> + <li>In the second example, things are a bit clearer — the label read out along with the input is "name star name edit text", and the labels are still read out separately. Things are still a bit confusing, but it's a bit better this time because the input has a label associated with it.</li> + <li>The third example is best — the actual label is read out all together, and the label read out with the input is "name star edit text".</li> +</ul> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: You might get slightly different results, depending on your screenreader. This was tested in VoiceOver (and NVDA behaves similarly). We'd love to hear about your experiences too.</p> +</div> + +<p><strong>Note</strong>: You can find this example on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/html/forms/html-form-structure/required-labels.html">required-labels.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/html-form-structure/required-labels.html">see it live also</a>). don't run the example with 2 or 3 of the versions uncommented — screenreaders will definitely get confused if you have multiple labels AND multiple inputs with the same ID!</p> + +<h2 dir="ltr" id="Estruturas_comuns_HTML_usadas_com_formulários">Estruturas comuns HTML usadas com formulários</h2> + +<p dir="ltr" id="tw-target-text">Além das estruturas específicas dos formulários HTML, é bom lembrar que os formulários são apenas HTML. Isso significa que você pode usar todo o poder do HTML para estruturar um formulário HTML.</p> + +<p>Como você pode ver nos exemplos, é comum envolver um <em>label</em> e seu <em>widget</em> com um elemento {{HTMLElement("div")}}. Os elementos {{HTMLElement("p")}} também são comumente usados, assim como as listas HTML (a última é mais comum para estruturar vários <em>checkboxes</em> ou <em>radio buttons</em>).</p> + +<p>Além do elemento {{HTMLElement("fieldset")}}, uma prática comum também é usar títulos HTML (por exemplo, {{htmlelement ("h1")}}, {{htmlelement ("h2")}}) e seção (por exemplo, {{htmlelement("section")}}) para estruturar um formulário complexo.</p> + +<p>Acima de tudo, cabe a você encontrar um estilo com o qual você acha confortável codificar e que também resulte em formulários acessíveis e utilizáveis.</p> + +<p>Temos cada seção desacoplada da funcionalidade contida nos elementos de {{htmlelement("section")}} e um {{htmlelement("fieldset")}} para conter os <em>radio buttons</em>.</p> + +<h3 id="Active_learning_building_a_form_structure">Active learning: building a form structure</h3> + +<p>Let's put these ideas into practice and build a slightly more involved form structure — a payment form. This form will contain a number of widget types that you may not yet understand — don't worry about this for now; you'll find out how they work in the next article (<a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/The_native_form_widgets">The native form widgets</a>). For now, read the descriptions carefully as you follow the below instructions, and start to form an appreciation of which wrapper elements we are using to structure the form, and why.</p> + +<ol> + <li>To start with, make a local copy of our <a href="https://github.com/mdn/learning-area/blob/master/html/introduction-to-html/getting-started/index.html">blank template file</a> and the <a href="https://github.com/mdn/learning-area/blob/master/html/forms/html-form-structure/payment-form.css">CSS for our payment form</a> in a new directory on your computer.</li> + <li>First of all, apply the CSS to the HTML by adding the following line inside the HTML {{htmlelement("head")}}: + <pre class="notranslate"><code><link href="payment-form.css" rel="stylesheet"></code></pre> + </li> + <li>Next, start your form off by adding the outer {{htmlelement("form")}} element: + <pre class="notranslate"><code><form> + +</form></code></pre> + </li> + <li>Inside the <code><form></code> tags, start by adding a heading and paragraph to inform users how required fields are marked: + <pre class="notranslate"><code><h1>Payment form</h1> +<p>Required fields are followed by <strong><abbr title="required">*</abbr></strong>.</p></code></pre> + </li> + <li>Next we'll add a larger section of code into the form, below our previous entry. Here you'll see that we are wrapping the contact information fields inside a distinct {{htmlelement("section")}} element. Moreover, we have a set of two radio buttons, each of which we are putting inside its own list ({{htmlelement("li")}}) element. Last, we have two standard text {{htmlelement("input")}}s and their associated {{htmlelement("label")}} elements, each contained inside a {{htmlelement("p")}}, plus a password input for entering a password. Add this code to your form now: + <pre class="notranslate"><code><section> + <h2>Contact information</h2> + <fieldset> + <legend>Title</legend> + <ul> + <li> + <label for="title_1"> + <input type="radio" id="title_1" name="title" value="M." > + Mister + </label> + </li> + <li> + <label for="title_2"> + <input type="radio" id="title_2" name="title" value="Ms."> + Miss + </label> + </li> + </ul> + </fieldset> + <p> + <label for="name"> + <span>Name: </span> + <strong><abbr title="required">*</abbr></strong> + </label> + <input type="text" id="name" name="username"> + </p> + <p> + <label for="mail"> + <span>E-mail: </span> + <strong><abbr title="required">*</abbr></strong> + </label> + <input type="email" id="mail" name="usermail"> + </p> + <p> + <label for="pwd"> + <span>Password: </span> + <strong><abbr title="required">*</abbr></strong> + </label> + <input type="password" id="pwd" name="password"> + </p> +</section></code></pre> + </li> + <li>Now we'll turn to the second <code><section></code> of our form — the payment information. Here we have three distinct widgets along with their labels, each contained inside a <code><p></code>. The first is a drop down menu ({{htmlelement("select")}}) for selecting credit card type. the second is an <code><input></code> element of type number, for entering a credit card number. The last one is an <code><input></code> element of type <code>date</code>, for entering the expiration date of the card (this one will come up with a date picker widget in supporting browsers, and fall back to a normal text input in non-supporting browsers). Again, enter the following below the previous section: + <pre class="notranslate"><code><section> + <h2>Payment information</h2> + <p> + <label for="card"> + <span>Card type:</span> + </label> + <select id="card" name="usercard"> + <option value="visa">Visa</option> + <option value="mc">Mastercard</option> + <option value="amex">American Express</option> + </select> + </p> + <p> + <label for="number"> + <span>Card number:</span> + <strong><abbr title="required">*</abbr></strong> + </label> + <input type="number" id="number" name="cardnumber"> + </p> + <p> + <label for="date"> + <span>Expiration date:</span> + <strong><abbr title="required">*</abbr></strong> + <em>formatted as yyyy/mm/dd</em> + </label> + <input type="date" id="date" name="expiration"> + </p> +</section></code></pre> + </li> + <li>The last section we'll add is a lot simpler, containing only a {{htmlelement("button")}} of type <code>submit</code>, for submitting the form data. Add this to the bottom of your form now: + <pre class="notranslate"><code><p> <button type="submit">Validate the payment</button> </p></code></pre> + </li> +</ol> + +<p>You can see the finished form in action below (also find it on GitHub — see our payment-form.html <a href="https://github.com/mdn/learning-area/blob/master/html/forms/html-form-structure/payment-form.html">source</a> and <a href="https://mdn.github.io/learning-area/html/forms/html-form-structure/payment-form.html">running live</a>):</p> + +<p>{{EmbedLiveSample("A_payment_form","100%",620, "", "Learn/HTML/Forms/How_to_structure_an_HTML_form/Example")}}</p> + +<h2 id="Summary">Summary</h2> + +<p>You now have all the knowledge you'll need to properly structure your HTML forms; the next article will dig into implementing all the different types of form widgets you'll want to use to collect information from your users.</p> + +<h2 id="See_Also">See Also</h2> + +<ul> + <li><a href="http://www.alistapart.com/articles/sensibleforms/" rel="external" title="http://www.alistapart.com/articles/sensibleforms/">A List Apart: <em>Sensible Forms: A Form Usability Checklist</em></a></li> +</ul> + +<p>{{PreviousMenuNext("Learn/HTML/Forms/Your_first_HTML_form", "Learn/HTML/Forms/The_native_form_widgets", "Learn/HTML/Forms")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form">Your first HTML form</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form">How to structure an HTML form</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/The_native_form_widgets">The native form widgets</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data">Sending form data</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation">Form data validation</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/How_to_build_custom_form_widgets">How to build custom form widgets</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript">Sending forms through JavaScript</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/HTML_forms_in_legacy_browsers">HTML forms in legacy browsers</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Styling_HTML_forms">Styling HTML forms</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Advanced_styling_for_HTML_forms">Advanced styling for HTML forms</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Property_compatibility_table_for_form_widgets">Property compatibility table for form widgets</a></li> +</ul> diff --git a/files/pt-br/learn/forms/index.html b/files/pt-br/learn/forms/index.html new file mode 100644 index 0000000000..15bd243566 --- /dev/null +++ b/files/pt-br/learn/forms/index.html @@ -0,0 +1,79 @@ +--- +title: Formulários da Web - Trabalhando com dados do usuário +slug: Web/Guide/HTML/Forms +tags: + - Aprender + - Funcionalidades + - Guía + - HTML + - Iniciante + - Web + - formulários +translation_of: Learn/Forms +--- +<div>{{LearnSidebar}}</div> + +<p class="summary"><span class="seoSummary">Este guia tem uma série de artigos que vão ajudar você a ficar craque em HTML forms.</span> HTML forms são ferramentas poderosas para interagir com usuários; contudo, por razões técnicas e históricas, <span>nem sempre é óbvio como usá-los em seu pleno potencia</span>l. Neste guia, vamos cobrir todos os aspectos dos HTML forms, da estrutura ao estilo, do manuseio de dados à widgets personalizados. Você vai aprender a desfrutar do grande poder que elas lhes oferecem!</p> + +<h2 id="Pré-requisitos">Pré-requisitos</h2> + +<p>Antes de iniciar este guia, você deve estar familiarizado com os conceitos da nossa <a href="/pt-BR/docs/Aprender/HTML/Introducao_ao_HTML">Introdução ao HTML</a>.</p> + +<div class="note"> +<p><strong>Dica</strong>: Se você está usando um computador/tablet/outro aparelho onde você não pode criar seus próprios arquivos, você pode testar (a maior parte) dos códigos de exemplo em uma ferramenta online como <a href="http://jsbin.com/">JSBin</a> ou <a href="https://thimble.mozilla.org/pt-BR/">Thimble</a>.</p> +</div> + +<h2 id="Guias_básicos">Guias básicos</h2> + +<p>Os seguintes guias te ensinarão todo o básico de formulários HTML, alcançando alguns tópicos ligeiramente mais avançados no caminho.</p> + +<dl> + <dt><a href="/en-US/docs/HTML/Forms/My_first_HTML_form" title="/en-US/docs/HTML/Forms/My_first_HTML_form">Meu primeiro formulário HTML</a></dt> + <dd>O primeiro artigo na série te instruirá em sua primeira vez criando um formulário HTML, incluindo o projeto/desenho de um formulário simples, implementação usando os elementos HTML corretos, estilização bem básica com CSS, e como os dados são enviados para um servidor.</dd> + <dt><a href="/en-US/docs/HTML/Forms/How_to_structure_an_HTML_form" title="/en-US/docs/HTML/Forms/How_to_structure_an_HTML_form"><span>Como estruturar um formulário HTML</span></a></dt> + <dd><span>Agora que o básico não é mais problema, daremos uma olhada mais aprofundada nos elementos usados para dar estrutura e significado para as diferentes partes de um formulário.</span></dd> + <dt><a href="/en-US/docs/HTML/Forms/The_native_form_widgets" title="/en-US/docs/HTML/Forms/The_native_form_widgets"><span>Os form widgets nativos </span></a></dt> + <dd>Veremos a funcionalidade de diferentes form widgets em detalhe, observando quais opções estão disponíveis para coletar diferentes tipos de dados.</dd> + <dt><a href="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data" title="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data"><span>Enviando e recuperando dados</span></a></dt> + <dd><span>Este artigo mostra o que acontece quando um usuário submete (envia) um formulário </span>—<span> para onde os dados vão, e o que fazer quando ele chegar lá? Também algumas das preocupações com segurança envolvida ao enviar dados em um formulário.</span></dd> + <dt><a href="/en-US/docs/HTML/Forms/Data_form_validation" title="/en-US/docs/HTML/Forms/Data_form_validation">Validação de dados nos formulários HTML</a></dt> + <dd>Enviar os dados não é o suficiente — também precisamos garantir que os dados que o usuário preenche num formulário está no formato correto que precisamos para processá-los com sucesso, e que não quebre nossas aplicações. Também queremos ajudar nossos usuários a preencher os formulários corretamente e não se sentirem frustrados ao usar nossos apps. Validação de dados nos ajuda a alcançar esses objetivos — este artigo te diz o que precisa saber.</dd> +</dl> + +<h2 id="Guias_avançados">Guias avançados</h2> + +<p>Estes guias passam por algumas técnicas mais avançadas, que você achará útil aprender quando já tiver dominado o básico.</p> + +<dl> + <dt><a href="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets" title="/en-US/docs/HTML/Forms/How_to_build_custom_form_widgets">Como criar widgets HTML form personalizados</a></dt> + <dd>Você encontrará alguns casos onde os widgets nativos não fornecem o que você precisa, por exemplo em função de estilo ou funcionalidade. Nestes casos, você precisará construir seu próprio widget de formulário a partir de HTML puro. Neste artigo explicamos como você pode fazer isso e o que precisa considerar ao fazer isso, com um estudo de caso prático.</dd> + <dt><a href="/en-US/docs/HTML/Forms/Sending_forms_through_JavaScript" title="/en-US/docs/HTML/Forms/Sending_forms_through_JavaScript">Enviando HTML forms através do JavaScript</a></dt> + <dd>Este artigo mostra formas de usar um formulário para montar um HTTP request e enviá-lo via JavaScript personalizado, em vez da forma de submissão padrão. Também apresenta razões pelas quais você quereria fazer isso, e as implicações de fazer dessa forma. (Veja também Usando o objeto FormData.)</dd> + <dt><a href="/en-US/docs/HTML/Forms/HTML_forms_in_legacy_browsers" title="/en-US/docs/HTML/Forms/HTML_forms_in_legacy_browsers">Formulários HTML para browsers antigos</a></dt> + <dd>Aborda detecção de funcionalidades, etc. Deveria ser movido para o módulo de testes multi-browser, já que a mesma coisa é abordada lá.</dd> + <dt><a href="/pt-BR/docs/HTML/Forms_in_HTML">Novidades em formulários no HTML5</a></dt> + <dd>Este artigo provê uma referência às novas adições aos formulários HTML na especificação HTML5.</dd> +</dl> + +<h2 id="Guias_de_estilização_de_formulários">Guias de estilização de formulários</h2> + +<p>Estes guias para estilizar formulários com CSS realmente deveriam estar nos tópicos sobre <a href="/pt-BR/docs/Aprender/CSS">CSS</a>, mas estamos mantendo-os aqui por enquanto até uma oportunidade apropriada de movê-los.</p> + +<dl> + <dt><a href="/en-US/docs/Web/Guide/HTML/Forms/Advanced_styling_for_HTML_forms" title="/en-US/docs/Advanced_styling_for_HTML_forms">Estilizando formulários HTML</a></dt> + <dd>Este artigo fornece uma introdução à personalização de estilos de formulário com CSS, incluindo todo o básico que você precisa para tarefas básicas de estilização.</dd> + <dt><a href="/en-US/docs/Web/Guide/HTML/Forms/Advanced_styling_for_HTML_forms" title="/en-US/docs/Advanced_styling_for_HTML_forms">Estilos avançados para HTML forms</a></dt> + <dd>Aqui vemos algumas técnicas mais avançadas de estilização de formulários que precisam ser usadas quando tiver de lidar com alguns dos elementos mais difíceis de personalizar.</dd> + <dt><a href="/en-US/docs/Property_compatibility_table_for_form_widgets" title="/en-US/docs/Property_compatibility_table_for_form_widgets">Tabela de compatibilidade das Propriedades dos widgets</a></dt> + <dd>Este último artigo fornece uma referência prática que te permite procurar quais propriedades CSS são compatíveis com quais elementos de formulário.</dd> +</dl> + +<h2 id="Avaliações">Avaliações</h2> + +<p>A definir.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/pt-BR/docs/Web/HTML/Element#Formulários">Referência de elementos de formulário HTML</a></li> +</ul> diff --git a/files/pt-br/learn/forms/sending_and_retrieving_form_data/index.html b/files/pt-br/learn/forms/sending_and_retrieving_form_data/index.html new file mode 100644 index 0000000000..c6eaaee29b --- /dev/null +++ b/files/pt-br/learn/forms/sending_and_retrieving_form_data/index.html @@ -0,0 +1,251 @@ +--- +title: Sending form data +slug: Web/Guide/HTML/Forms/Sending_and_retrieving_form_data +translation_of: Learn/Forms/Sending_and_retrieving_form_data +--- +<p>Em muitos casos, a finalidade de <a href="/en-US/docs/HTML/Forms" title="/en-US/docs/HTML/Forms">HTML Form</a> Um é enviar dados para um servidor. O servidor processa os dados e envia uma resposta ao usuário. Isso parece simples, mas é importante manter algumas coisas em mente para garantir que os dados não danifiquem o servidor ou causem problemas para seus usuários.</p> + +<h2 id="Para_onde_vão_os_dados">Para onde vão os dados?</h2> + +<p>Aqui nós discutiremos o que acontece com os dadosquando um formulário é enviado.</p> + +<h3 id="Sobre_a_arquitetura_cliente_servidor">Sobre a arquitetura cliente / servidor</h3> + +<p>A web é baseada em uma arquitetura cliente / servidor muito básica que pode ser resumida da seguinte forma: um cliente (normalmente um navegador da Web) envia um pedido a um servidor (na maioria das vezes um servidor web como <a href="http://httpd.apache.org/" rel="external" title="http://www.apache.org/">Apache</a>, <a href="http://nginx.com/" rel="external" title="http://nginx.com/">Nginx</a>, <a href="http://www.iis.net/" rel="external" title="http://www.iis.net/">IIS</a>, <a href="http://tomcat.apache.org/" rel="external" title="http://tomcat.apache.org/">Tomcat</a>, etc.), usando o <a href="/en-US/docs/HTTP" title="/en-US/docs/HTTP">HTTP protocol</a>. O servidor responde a solicitação usando o mesmo protocolo.</p> + +<p><img alt="A basic schema of the Web client/server architecture" src="/files/4291/client-server.png" style="height: 141px; width: 400px;"></p> + +<p>No lado do cliente, um formulário HTML é nada mais do que uma maneira conveniente e amigável para configurar uma solicitação HTTP para enviar dados para um servidor. Isso permite que o usuário forneça informações a serem entregues na solicitação HTTP.</p> + +<h3 id="No_lado_do_cliente_definindo_como_enviar_os_dados">No lado do cliente: definindo como enviar os dados</h3> + +<p>O elemento {{HTMLElement("form")}} define como os dados serão enviados. Todos os seus atributos são projetados para permitir que você configure o pedido a ser enviado quando um usuário acessa um botão de envio. Os dois atributos mais importantes são:{{htmlattrxref("action","form")}} e {{htmlattrxref("method","form")}}.</p> + +<h4 id="o_atributo_htmlattrxref(actionform)">o atributo {{htmlattrxref("action","form")}}</h4> + +<p>Este atributo define para onde os dados são enviados. Seu valor deve ser um URL válido. Se esse atributo não for fornecido, os dados serão enviados para o URL da página que contém o formulário.</p> + +<h5 id="Exemplos">Exemplos</h5> + +<p>Neste exemplo, os dados são enviados para http://foo.com:</p> + +<pre class="brush: html"><form action="http://foo.com"></pre> + +<p class="brush: html">Aqui, os dados são enviados para o mesmo servidor que hospeda a página do formulário, mas para um URL diferente no servidor:</p> + +<pre class="brush: html"><form action="/somewhere_else"></pre> + +<p class="brush: html">Quando especificado sem atributos, como abaixo, o atributo {{HTMLElement("form")}} faz com que os dados sejam enviados para a página que inclui o formulário:</p> + +<pre class="brush: html"><form></pre> + +<p class="brush: html">Muitas páginas mais antigas usam a seguinte notação para indicar que os dados devem ser enviados para a mesma página que contém o formulário; Isso era necessário porque até HTML5, o atributo {{htmlattrxref ( "action", "form")}} era obrigatório. Isso não é mais necessário.</p> + +<pre class="brush: html"><form action="#"></pre> + +<div class="note"> +<p><strong>Nota: É possível especificar um URL que use o protocolo HTTPS (HTTP seguro). Quando você fizer isso, os dados são criptografados junto com o resto da solicitação, mesmo se o formulário em si é hospedado em uma página insegura acessada usando HTTP. Por outro lado, se o formulário estiver hospedado na página segura, mas você especificar um URL HTTP inseguro com o atributo {{htmlattrxref ( "action", "form")}}, todos os navegadores exibirão um aviso de segurança para o usuário cada vez que Tente enviar dados porque os dados não serão criptografados.</strong></p> +</div> + +<h4 id="o_atributo_htmlattrxref(methodform)">o atributo {{htmlattrxref("method","form")}}</h4> + +<p>Este atributo define como os dados são enviados. o <a href="/en-US/docs/HTTP" title="/en-US/docs/HTTP">HTTP protocol</a> </p> + +<p>Fornece várias maneiras de executar um pedido; Os dados de formulários HTML podem ser enviados através de pelo menos dois deles: o método GET eo método POST.</p> + +<p>Para entender a diferença entre esses dois métodos, vamos dar um passo atrás e examinar como funciona o HTTP. Cada vez que você deseja acessar um recurso na Web, o navegador envia uma solicitação para um URL. Uma solicitação HTTP consiste em duas partes: um cabeçalho que contém um conjunto de metadados globais sobre as capacidades do navegador e um corpo que pode conter informações necessárias ao servidor para processar a solicitação específica.</p> + +<h5 id="O_método_GET">O método GET</h5> + +<p>O método GET é o método usado pelo navegador para pedir ao servidor para enviar de volta um determinado recurso: "Hey servidor, eu quero obter este recurso." Nesse caso, o navegador envia um corpo vazio. Como o corpo está vazio, se um formulário é enviado usando esse método, os dados enviados para o servidor são anexados ao URL.</p> + +<h6 id="Exemplo_Considere_o_seguinte_formulário">Exemplo<br> + Considere o seguinte formulário:</h6> + +<pre class="brush: html"><form action="http://foo.com" method="get"> + <input name="say" value="Hi"> + <input name="to" value="Mom"> + <button>Envie meus cumprimentos</button> +</form></pre> + +<p>Com o método GET, a solicitação HTTP tem esta aparência:</p> + +<pre>GET /?say=Hi&to=Mom HTTP/1.1 +Host: foo.com</pre> + +<h5 id="O_método_POST">O método POST</h5> + +<p>O método POST é um pouco diferente. É o método que o navegador envia ao servidor para pedir uma resposta que leva em conta os dados fornecidos no corpo da solicitação HTTP: "Hey servidor, dê uma olhada nesses dados e envie-me de volta um resultado apropriado". Se um formulário é enviado usando esse método, os dados são anexados ao corpo do pedido HTTP.</p> + +<h6 id="Exemplo">Exemplo</h6> + +<p>Considere esta forma (a mesma acima):</p> + +<pre class="brush: html"><form action="http://foo.com" method="post"> + <input name="say" value="Hi"> + <input name="to" value="Mom"> + <button>Send my greetings</button> +</form></pre> + +<p>Quando enviado usando o método POST, o pedido HTTP se parece com isto:</p> + +<pre>POST / HTTP/1.1 +Host: foo.com +Content-Type: application/x-www-form-urlencoded +Content-Length: 13 + +say=Hi&to=Mom</pre> + +<p>O cabeçalho Content-Length indica o tamanho do corpo eo cabeçalho Content-Type indica o tipo de recurso enviado para o servidor. Vamos discutir esses cabeçalhos em um pouco.</p> + +<p>Obviamente, as solicitações HTTP nunca são exibidas para o usuário (se você quiser vê-las, você precisa usar ferramentas como o Firefox <a href="/en-US/docs/Tools/Web_Console" title="/en-US/docs/Tools/Web_Console">Web Console</a> ou o <a href="https://developers.google.com/chrome-developer-tools/" title="https://developers.google.com/chrome-developer-tools/">Chrome Developer Tools</a>). A única coisa exibida para o usuário é o URL chamado. Assim, com uma solicitação GET, o usuário verá os dados em sua barra de URL, mas com uma solicitação POST, eles não. Isso pode ser muito importante por duas razões:</p> + +<ol> + <li>Se você precisar enviar uma senha (ou qualquer parte sensível de dados), nunca use o método GET ou corre o risco de exibi-lo na barra de URL.</li> + <li>Se você precisar enviar uma grande quantidade de dados, o método POST é preferido porque alguns navegadores limitam o tamanho dos URLs. Além disso, muitos servidores limitam o comprimento dos URLs que aceitam.</li> +</ol> + +<h3 id="No_lado_do_servidor_recuperar_os_dados">No lado do servidor: recuperar os dados</h3> + +<p>Seja qual for o método HTTP escolhido, o servidor recebe uma string que será analisada para obter os dados como uma lista de pares chave / valor. A maneira como você acessa essa lista depende da plataforma de desenvolvimento que você usa e de quaisquer frameworks específicos que você possa usar com ele. A tecnologia que você usa também determina como as chaves duplicadas são manipuladas; Freqüentemente, o valor recebido mais recentemente para uma determinada chave recebe prioridade.</p> + +<h4 id="Exemplo_PHP_Bruto">Exemplo: PHP Bruto</h4> + +<p>O PHP oferece alguns objetos globais para acessar os dados. Supondo que você tenha usado o método POST, o exemplo a seguir apenas leva os dados e exibe-o para o usuário. Claro, o que você faz com os dados depende de você. Você pode exibi-lo, armazená-lo em um banco de dados, enviá-los por e-mail, ou processá-lo de alguma outra maneira.</p> + +<pre class="brush: php"><?php + // The global $_POST variable allows you to access the data sent with the POST method + // To access the data sent with the GET method, you can use $_GET + $say = htmlspecialchars($_POST['say']); + $to = htmlspecialchars($_POST['to']); + + echo $say, ' ', $to;</pre> + +<p>Este exemplo exibe uma página com os dados enviados. Em nosso exemplo de antes, a saída seria:</p> + +<pre>Oi Mãe</pre> + +<h4 id="Example_Python_Bruto">Example: Python Bruto</h4> + +<p>This example uses Python to do the same thing--display the provided data on a web page. It uses the <a href="http://docs.python.org/3/library/cgi.html" rel="external" title="http://docs.python.org/3/library/cgi.html">CGI Python package</a> to access the form data.</p> + +<pre class="brush: python">#!/usr/bin/env python +import html +import cgi +import cgitb; cgitb.enable() # for troubleshooting + +print("Content-Type: text/html") # HTTP header to say HTML is following +print() # blank line, end of headers + +form = cgi.FieldStorage() +say = html.escape(form["say"].value); +to = html.escape(form["to"].value); + +print(say, " ", to)</pre> + +<p>O resultado é o mesmo que com o PHP:</p> + +<pre>Oi Mãe</pre> + +<h4 id="Outros_idiomas_e_frameworks">Outros idiomas e frameworks</h4> + +<p>Há muitas outras tecnologias do lado do servidor que você pode usar para o tratamento de formulários, incluindo <a href="/en-US/docs/" title="/en-US/docs/">Perl</a>, <a href="/en-US/docs/" title="/en-US/docs/">Java</a>, <a href="http://www.microsoft.com/net" title="http://www.microsoft.com/net">.Net</a>, <a href="/en-US/docs/" title="/en-US/docs/">Ruby</a>, etc. Basta escolher o que você mais gosta. Dito isto, é importante notar que é muito incomum usar essas tecnologias diretamente porque isso pode ser complicado. É mais comum usar um dos muitos frameworks agradáveis que facilitam o manuseio de formulários, como:</p> + +<ul> + <li><a href="http://symfony.com/" rel="external" title="http://symfony.com/">Symfony</a> Para PHP</li> + <li><a href="https://www.djangoproject.com/" rel="external" title="https://www.djangoproject.com/">Django</a> Para Python</li> + <li><a href="http://rubyonrails.org/" rel="external" title="http://rubyonrails.org/">Ruby On Rails</a> Para Ruby</li> + <li><a href="http://grails.org/" rel="external" title="http://grails.org/">Grails</a> Para Java</li> + <li>etc.</li> +</ul> + +<p>Vale a pena notar que mesmo usando essas estruturas, trabalhar com formulários não é necessariamente fácil. Mas é muito melhor, e você vai economizar muito tempo.</p> + +<h2 id="Um_caso_especial_enviar_arquivos">Um caso especial: enviar arquivos</h2> + +<p>Arquivos são um caso especial com formulários HTML. Eles são dados binários - ou considerados como tal - onde todos os outros dados são dados de texto. Porque HTTP é um protocolo de texto, há requisitos especiais para manipular dados binários.</p> + +<h3 id="o_htmlattrxref(enctypeform)_atributo">o {{htmlattrxref("enctype","form")}} atributo</h3> + +<p>Esse atributo permite especificar o valor do cabeçalho HTTP Content-Type. Este cabeçalho é muito importante porque informa ao servidor que tipo de dados está sendo enviado. Por padrão, seu valor é application / x-www-form-urlencoded. Em termos humanos, isso significa: "Este é o formulário de dados que foi codificado em forma de URL."</p> + +<p>Mas se você quiser enviar arquivos, você precisa fazer duas coisas:</p> + +<ul> + <li>Colocou o {{htmlattrxref("method","form")}} Atributo para POST porque o conteúdo do arquivo não pode ser colocado dentro de um parâmetro de URL usando um formulário.</li> + <li>Defina o valor de {{htmlattrxref("enctype","form")}} Para multipart / form-data porque os dados serão divididos em várias partes, uma para cada arquivo mais uma para o texto do corpo do formulário que pode ser enviado com eles.</li> +</ul> + +<p>Por exemplo:</p> + +<pre class="brush: html"><form method="post" enctype="multipart/form-data"> + <input type="file" name="myFile"> + <button>Send the file</button> +</form></pre> + +<div class="note"> +<p><strong>Nota: Alguns navegadores suportam</strong>{{htmlattrxref("multiple","input")}} Atributo no {{HTMLElement("input")}} Elemento para enviar mais de um arquivo com apenas um elemento de entrada. Como o servidor lida com esses arquivos realmente depende da tecnologia usada no servidor. Como mencionado anteriormente, usando um quadro fará sua vida muito mais fácil.</p> +</div> + +<div class="warning"> +<p><strong>Aviso: Muitos servidores são configurados com um limite de tamanho para arquivos e solicitações HTTP, a fim de evitar abusos. É importante verificar esse limite com o administrador do servidor antes de enviar um arquivo.</strong></p> +</div> + +<h2 id="Preocupações_com_segurança">Preocupações com segurança</h2> + +<p>Cada vez que você envia dados para um servidor, você precisa considerar a segurança. Formulários HTML são um dos primeiros vetores de ataque contra servidores. Os problemas nunca vêm dos formulários HTML em si; Eles vêm de como o servidor manipula dados.</p> + +<h3 id="Falhas_de_segurança_comuns">Falhas de segurança comuns</h3> + +<p>Dependendo do que você está fazendo, existem alguns problemas de segurança muito conhecidos:</p> + +<h4 id="XSS_e_CSRF">XSS e CSRF</h4> + +<p>Cross-Site Scripting (XSS) e Cross-Site Request Forgery (CSRF) são tipos comuns de ataques que ocorrem quando você exibe dados enviados por um usuário para o usuário ou para outro usuário.</p> + +<p>O XSS permite que os invasores injetem scripts do lado do cliente em páginas da Web vistas por outros usuários. Uma vulnerabilidade de scripts entre sites pode ser usada por atacantes para ignorar controles de acesso, como o <a href="/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript" title="/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript">same origin policy</a>. O efeito desses ataques pode variar de um pequeno incômodo a um risco de segurança significativo.</p> + +<p>CSRF são semelhantes aos ataques XSS, já que eles começam da mesma maneira - injetando script do lado do cliente em páginas da Web - mas seu destino é diferente. Os invasores do CSRF tentam aumentar os privilégios para aqueles de um usuário com privilégios mais altos (como um administrador do site) para executar uma ação que não deve ser capaz de fazer (por exemplo, enviar dados para um usuário não confiável).</p> + +<p>Os ataques XSS exploram a confiança que um usuário tem para um site, enquanto os ataques CSRF exploram a confiança que um site tem para seus usuários.</p> + +<p>To prevent these attacks, you should always check the data a user sends to your server and (if you need to display it) try not to display the HTML content as provided by the user. Intead, you should process the user-provided data so you don't display it verbatim. <span style="line-height: 1.5;"> Almost all frameworks on the market today implement a minimal filter that removes the HTML {{HTMLElement("script")}}, {{HTMLElement("iframe")}} and {{HTMLElement("object")}} elements from data sent by any user. This helps to mitigate the risk, but doesn't necessarily eradicate it.</span></p> + +<h4 id="SQL_injection">SQL injection</h4> + +<p>SQL injection is a type of attack that tries to perform actions on a database used by the target web site. This typically involves sending an SQL request in the hope that the server will execute it (many times when the application server tries to store the data). This is actually <a href="https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project" rel="external" title="https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project">one of the main vector attacks against web sites</a>.</p> + +<p>The consequences can be terrible, ranging from data loss to access to a whole infrastructure by using privilege escalation. This is a very serious threat and you should never store data sent by a user without performing some sanitization (for example, by using <code><a href="http://www.php.net/manual/en/function.mysql-real-escape-string.php" rel="external" title="http://www.php.net/manual/en/function.mysql-real-escape-string.php">mysql_real_escape_string()</a></code> on a PHP/MySQL infrastructure).</p> + +<h4 id="HTTP_header_injection_and_email_injection">HTTP header injection and email injection</h4> + +<p>These kinds of attacks can occur when your application builds HTTP headers or emails based on the data input by a user on a form. These won't directly damage your server or affect your users, but they are an open door to deeper problems such as session hijacking or phishing attacks.</p> + +<p>These attacks are mostly silent, and can turn your server into a <a href="http://en.wikipedia.org/wiki/Zombie_(computer_science)" rel="exernal" title="http://en.wikipedia.org/wiki/Zombie_(computer_science)">zombie</a>.</p> + +<h3 id="Be_paranoid_Never_trust_your_users">Be paranoid: Never trust your users</h3> + +<p>So, how do you fight these threats? This is a topic far beyond this guide, but there are a few rules to keep in mind. The most important rule is: never ever trust your users, including yourself; even a trusted user could have been hijacked.</p> + +<p>All data that comes to your server must be checked and sanitized. Always. No exception.</p> + +<ul> + <li>Escape potentially dangerous characters. The specific characters you should be cautious with vary depending on the context in which the data is used and the server platform you employ, but all server-side languages have functions for this.</li> + <li>Limit the incoming amount of data to allow only what's necessary.</li> + <li>Sandbox uploaded files (store them on a different server and allow access to the file only through a different subdomain or even better through a fully different domain name).</li> +</ul> + +<p>You should avoid many/most problems if you follow these three rules, but it's always a good idea to get a security review performed by a competent third party. Don't assume that you've seen all the possible problems.</p> + +<h2 id="Conclusion">Conclusion</h2> + +<p>As you can see, sending form data is easy, but securing an application can be tricky. Just remember that a front-end developer is not the one who should define the security model of the data. Yes, as we'll see, it's possible to <a href="/en-US/docs/HTML/Forms/Data_form_validation" title="/en-US/docs/HTML/Forms/Data_form_validation">perform client side data validation</a> but the server can't trust this validation because it has no way to truly know what really happens on the client side.</p> + +<h2 id="See_also">See also</h2> + +<p>If you want to learn more about securing a web application, you can dig into these resources:</p> + +<ul> + <li><a href="https://www.owasp.org/index.php/Main_Page" rel="external" title="https://www.owasp.org/index.php/Main_Page">The Open Web Application Security Project (OWASP)</a></li> + <li><a href="http://shiflett.org/" rel="external" title="http://shiflett.org/">Chris Shiflett's blog about PHP Security</a></li> +</ul> diff --git a/files/pt-br/learn/forms/your_first_form/index.html b/files/pt-br/learn/forms/your_first_form/index.html new file mode 100644 index 0000000000..31ef58aa7c --- /dev/null +++ b/files/pt-br/learn/forms/your_first_form/index.html @@ -0,0 +1,270 @@ +--- +title: Meu primeiro formulário HTML +slug: Web/Guide/HTML/Forms/Meu_primeiro_formulario_HTML +translation_of: Learn/Forms/Your_first_form +--- +<p>Este é um artigo introdutório para formulários HTML. Através de um simples formulário de contato, nós veremos os requisitos básicos para construir formulários HTML. Esse artigo assume que você não sabe nada sobre formulários HTML, mas presume que você conhece o <a href="/pt-BR/docs/HTML/Introduction">básico de HTML</a> e <a href="/pt-BR/docs/Web/CSS/Getting_Started" title="/en-US/docs/CSS/Getting_Started">CSS</a>.</p> + +<h2 id="Antes_de_começarmos">Antes de começarmos</h2> + +<h3 id="O_que_são_formulários_HTML">O que são formulários HTML?</h3> + +<p>Formulários HTML são um dos principais pontos de interação entre um usuário e um web site ou aplicativo. Eles permitem que os usuários enviem dados para o web site. Na maior parte do tempo, os dados são enviados para o servidor da web, mas a página da web também pode interceptar para usá-los por conta própria.</p> + +<p>Um formulário HTML é feito de um ou mais widgets. Esses widgets podem ser campos de texto (linha única ou de várias linhas), caixas de seleção, botões, checkboxes ou radio buttons. A maior parte do tempo, estes elementos são emparelhados com uma legenda que descreve o seu objetivo.</p> + +<h3 id="O_que_você_precisa_para_trabalhar_com_formulários">O que você precisa para trabalhar com formulários?</h3> + +<p>Você não precisa de nada mais do que o que é requisitado para trabalhar com HTML: Um editor de texto e um navegador. É claro, que se você esta acostumado a usá-los você pode ter vantagens de uma IDE completa como <a href="http://www.microsoft.com/visualstudio" rel="external" title="http://www.microsoft.com/visualstudio">Visual Studio</a>, <a href="http://www.eclipse.org" rel="external" title="http://www.eclipse.org">Eclipse</a>, <a href="http://www.aptana.com/" rel="external" title="http://www.aptana.com/">Aptana</a>, etc., mas cabe somente a você.</p> + +<p>A principal diferença entre um formulário de HTML e um documento regular de HTML é que, maioria das vezes, o dado coletado é enviado ao servidor. Nesse caso, você precisa configurar um servidor web para receber e processar os dados. Como configurar um servidor está além do escopo deste artigo, mas se você quer saber mais, consulte o artigo dedicado a este tema: <a href="/en-US/docs/HTML/Forms/Sending_and_Retrieving_form_data">Envio e recuperação de dados do formulário</a>.</p> + +<h2 id="Desenhando_seu_formulário">Desenhando seu formulário</h2> + +<p>Antes de começar a codificar, é sempre melhor dar um passo atrás e tomar o tempo para pensar sobre o seu formulário. Desenhando um rascunho rápido irá ajudar a definir o conjunto correto de dados que você quer perguntar ao usuário. De um ponto de vista da experiência do usuário (UX), é importante lembrar que quanto maior o seu formulário, maior o risco de perder os usuários. Mantenha o formuário simples e mantenha o foco: <strong>peça apenas o que é absolutamente necessário</strong>.<br> + A criação de formulários é um passo importante quando você está construindo um site ou um aplicativo. Está além do escopo deste artigo cobrir as formas, mas se você quiser se aprofundar neste tópico você deve ler os seguintes artigos:</p> + +<ul> + <li>A Smashing Magazine tem <a href="http://uxdesign.smashingmagazine.com/tag/forms/">ótimos artigos sobre UX</a> nos formulários, mas talvez o mais importante é o <a href="https://translate.google.com/translate?sl=en&tl=pt&js=y&prev=_t&hl=pt-BR&ie=UTF-8&u=http%3A%2F%2Fwww.smashingmagazine.com%2Ftag%2Fforms%2F&edit-text=&act=url">Extenso Guia para a usabilidade em formulários Web</a>.</li> + <li>UXMatters também é um recurso muito atencioso com bons conselhos de <a href="https://translate.google.com/translate?sl=en&tl=pt&js=y&prev=_t&hl=pt-BR&ie=UTF-8&u=http%3A%2F%2Fwww.uxmatters.com%2Fmt%2Farchives%2F2012%2F05%2F7-basic-best-practices-for-buttons.php&edit-text=&act=url">melhores práticas básicas </a>para conceitos complexos, tais como <a href="https://translate.google.com/translate?hl=pt-BR&sl=en&tl=pt&u=http%3A%2F%2Fwww.uxmatters.com%2Fmt%2Farchives%2F2010%2F03%2Fpagination-in-web-forms-evaluating-the-effectiveness-of-web-forms.php">formulários de várias páginas </a>.</li> +</ul> + +<p>Neste artigo vamos construir um formulário de contato simples. Vamos fazer um esboço.</p> + +<p><img alt="The form to build, roughly sketch" src="/files/4579/form-sketch-low.jpg" style="border-style: solid; border-width: 1px; height: 352px; width: 400px;"></p> + +<p>O nosso formulário terá três campos de texto e um botão. Basicamente, pedimos ao usuário o seu nome, seu e-mail e a mensagem que deseja enviar. Ao apertar o botão apenas irá enviar os dados para o servidor web.</p> + +<h2 id="Sujar_as_mãos_com_HTML">Sujar as mãos com HTML</h2> + +<p><br> + Ok, agora estamos prontos para ir para o código HTML do nosso formulário. Para construir o nosso formulário de contato, vamos utilizar os seguintes elementos {{HTMLElement("form")}} , {{HTMLElement("label")}} , {{HTMLElement("input")}} , {{HTMLElement("textarea")}} , e {{HTMLElement("button")}} .</p> + +<h3 id="O_Elemento_HTMLElement(form)">O Elemento {{HTMLElement("form")}} </h3> + +<p>Todos formulários HTML começam com um elemento {{HTMLElement("form")}} como este:</p> + +<pre class="brush:html;"><form action="/pagina-processa-dados-do-form" method="post"> + +</form></pre> + +<p>Este elemento define um formulário. É um elemento de container como um elemento {{HTMLElement ("div")}} ou {{HTMLElement ("p")}} , mas ele também suporta alguns atributos específicos para configurar a forma como o formulário se comporta. Todos os seus atributos são opcionais, mas é considerada a melhor prática sempre definir pelo menos o atributo <code><em>action </em></code>e o atributo <code><em>method</em></code>.</p> + +<ul> + <li>O atributo <em><strong>action </strong></em>define o local (uma URL) em que os dados recolhidos do formulário devem ser enviados.</li> + <li>O atributo <em><strong>method</strong></em> define qual o método HTTP para enviar os dados (ele pode ser "<strong>GET</strong>" ou "<strong>POST</strong>" (veja as diferenças <a href="http://www.comocriarsites.com/html/como-funciona-os-metodos-get-e-post-diferencas/">aqui</a>).</li> +</ul> + +<p>Se você quiser se aprofundar em como esses atributos funcionam, está detalhado no artigo <a href="/pt-BR/docs/HTML/Forms/Sending_and_retrieving_form_data">Enviando e recebendo dados de um formulário</a></p> + +<h3 id="Adicionar_campos_com_os_elementos_HTMLElement(label)_HTMLElement(input)_e_HTMLElement(textarea)">Adicionar campos com os elementos {{HTMLElement("label")}} , {{HTMLElement("input")}} , e {{HTMLElement("textarea")}} </h3> + +<p>O nosso formulário de contato é muito simples e contém três campos de texto, cada um com uma etiqueta. O campo de entrada para o nome será um campo básico texto de linha única("input"); o campo de entrada do e-mail será um campo de texto com uma única linha("input") que vai aceitar apenas um endereço de e-mail; o campo de entrada para a mensagem será um campo de texto de várias linhas("textarea").</p> + +<p>Em termos de código HTML, teremos algo assim:</p> + +<pre class="brush:html;"><form action="/pagina-processa-dados-do-form" method="post"> + <div> + <label for="nome">Nome:</label> + <input type="text" id="nome" /> + </div> + <div> + <label for="email">E-mail:</label> + <input type="email" id="email" /> + </div> + <div> + <label for="msg">Mensagem:</label> + <textarea id="msg"></textarea> + </div> +</form></pre> + +<p>Os elementos {{HTMLElement ("div")}} estão lá para estruturar nosso código e deixar a estilização mais fácil (ver abaixo). Observe o uso do atributo <em><strong>for</strong></em> em todos os elementos {{HTMLElement ("label")}} ; é uma maneira para vincular uma <strong><em>label</em></strong> à um campo do formulário. Este atributo faz referência ao <em><strong>id</strong></em> do campo correspondente. Há algum benefício para fazer isso, é a de permitir que o usuário clique no rótulo para ativar o campo correspondente. Se você quer uma melhor compreensão dos outros benefícios deste atributo, tudo é detalhado no artigo: <a href="/en-US/docs/HTML/Forms/How_to_structure_an_HTML_form" title="/en-US/docs/HTML/Forms/How_to_structure_an_HTML_form">How to structure an HTML form</a>(en).</p> + +<p>No elemento {{HTMLElement ("input")}} , o atributo mais importante é o atributo <code><em><strong>type</strong></em></code>. Esse atributo é extremamente importante porque define a forma como o elemento {{HTMLElement ("input")}} se comporta. Ele pode mudar radicalmente o elemento, então preste atenção a ele. Se você quiser saber mais sobre isso, leia o artigo <a href="/en-US/docs/HTML/Forms/The_native_form_widgets" rel="external" title="/en-US/docs/HTML/Forms/The_native_forms_widgets">native form widgets</a>. Em nosso exemplo, nós usamos somente o <code><strong>type<em>=</em></strong>"<em><strong>text</strong></em>",</code> valor padrão para este atributo. Ele representa um campo de texto com uma única linha que aceita qualquer tipo de texto sem controle ou validação. Nós também usamos o <code><strong>type<em>=</em></strong>"<strong><em>email</em></strong>"</code> que define um campo de texto com uma única linha que só aceita um endereço de e-mail bem-formados. Este último valor torna um campo de texto básico em uma espécie de campo "inteligente", que irá realizar alguns testes com os dados digitados pelo usuário. Se você quiser saber mais sobre a validação de formulário, detalharemos melhor no artigo <a href="/en-US/docs/HTML/Forms/Data_form_validation" title="/en-US/docs/HTML/Forms/Data_form_validation">Validação de dados de formulário</a>.</p> + +<p>Por último, mas não menos importante, observe a sintaxe de <code><strong><input /></strong> </code> e <code><strong><textarea> </ textarea></strong>.</code> Esta é uma das esquisitices do HTML. A tag<strong> <code><input /></code> </strong>é um elemento que se auto-fecha, o que significa que se você quiser encerrar formalmente o elemento, você tem que adicionar uma barra "<strong>/</strong>" no final do próprio elemento e não uma tag de fechamento. No entanto, o tipo {{HTMLElement ("textarea")}} não é um elemento de auto-fechamento, então você tem que fechá-lo com a tag final adequada. Isso tem um impacto sobre um recurso específico de formulários HTML: a maneira como você define o valor padrão. Para definir o valor padrão de um elemento {{HTMLElement ("input")}} você tem que usar o atributo <code><em><strong>value</strong></em> </code>como este:</p> + +<pre class="brush:html;"><input type="text" value="Por padrão, este elemento será preenchido com este texto " /></pre> + +<p>Pelo contrário, se você deseja definir o valor padrão de um elemento {{HTMLElement ("textarea")}} , você só tem que colocar esse valor padrão no meio das tags, entre tag inicial e a tag final do elemento {{HTMLElement ("textarea")}} , como abaixo:</p> + +<pre class="brush:html;"><textarea>Por padrão, este elemento será preenchido com este texto </textarea></pre> + +<h3 id="E_um_elemento_HTMLElement(button)_para_concluir">E um elemento {{HTMLElement("button")}} para concluir</h3> + +<p>O nosso formulário está quase pronto; nós temos apenas que adicionar um botão para permitir que o usuário envie seus dados depois de ter preenchido o formulário. Isto é simplesmente feito usando o elemento {{HTMLElement ("button")}} :</p> + +<pre class="brush:html;"><form action="/pagina-processa-dados-do-form" method="post"> + <div> + <label for="name">Nome:</label> + <input type="text" id="name" /> + </div> + <div> + <label for="mail">E-mail:</label> + <input type="email" id="mail" /> + </div> + <div> + <label for="msg">Mensagem:</label> + <textarea id="msg"></textarea> + </div> + <div class="button"> + <button type="submit">Enviar sua mensagem</button> + </div> +</form></pre> + +<p>Um botão pode ser de três tipos: <strong><code>submit</code></strong>, <strong><code>reset</code></strong>, ou <strong><code>button</code></strong>.</p> + +<ul> + <li>Um clique sobre um botão de <strong><code>submit</code> </strong>envia os dados do formulário para a página de web definida pelo atributo <code><strong>action </strong></code>do elemento {{HTMLElement ("form")}} .</li> + <li>Um clique sobre um botão de <strong><code>reset </code></strong>redefine imediatamente todos os campos do formulário para o seu valor padrão. De um ponto de vista na usabilidade do usuário(UX), isso é considerado uma má prática.</li> + <li>Um clique em um botão do tipo <code><strong>button</strong></code> faz ...ops, nada! Isso soa bobo, mas é incrivelmente útil para construir botões personalizados com JavaScript, ou seja, ele pode assumir qualquer comportamento através desta linguagem.</li> +</ul> + +<p>Note que você também pode usar o elemento {{HTMLElement ("input")}} com o tipo correspondente para produzir um botão. A principal diferença com o elemento {{HTMLElement ("button")}} é que o elemento {{HTMLElement ("input")}} permite apenas texto sem formatação como seu valor, enquanto que o elemento {{HTMLElement ("button")}} permite que o conteúdo HTML completo como seu valor.</p> + +<h2 id="Vamos_deixar_um_pouco_mais_legal_com_CSS">Vamos deixar um pouco mais legal com CSS</h2> + +<p>Agora que temos o nosso formulário HTML, se você olhar para ele em seu navegador favorito, você vai ver que ele parece meio feio.</p> + +<p><img alt="" src="/files/4049/form-no-style.png" style="height: 170px; width: 534px;"></p> + +<p>Vamos deixar ele um pouco mais legal com os códigos CSS a seguir:</p> + +<p>Vamos começar com o próprio formulário; vamos centralizá-lo e torná-lo visível com uma borda:</p> + +<pre class="brush:css;">form { + /* Apenas para centralizar o form na página */ + margin: 0 auto; + width: 400px; + /* Para ver as bordas do formulário */ + padding: 1em; + border: 1px solid #CCC; + border-radius: 1em; +}</pre> + +<p>Então, adicionaremos algum espaço entre cada conjunto de campos do form:</p> + +<pre class="brush:css;">form div + div { + margin-top: 1em; +}</pre> + +<p>Agora vamos focar nas <strong><code><em>labels</em></code></strong>. Para fazer o nosso formulário mais legível, é considerada a melhor prática ter todas as etiquetas do mesmo tamanho e alinhadas do mesmo lado. Nesse caso, vamos alinhá-los para a direita, mas em alguns casos, o alinhamento à esquerda pode ficar bem também.</p> + +<pre class="brush:css;">label { + /*Para ter certeza que todas as labels tem o mesmo tamanho e estão propriamente alinhadas */ + display: inline-block; + width: 90px; + text-align: right; +}</pre> + +<p>Uma das coisas mais difíceis de fazer em formulários HTML são os estilo dos próprios campos. Os campos de texto são fáceis de estilizar, mas alguns outros campos não são. Se você quiser saber mais sobre estilização de formulários HTML, leia o artigo <a href="/en-US/docs/HTML/Forms/Styling_HTML_forms" title="/en-US/docs/HTML/Forms/Styling_HTML_forms">Styling HTML forms</a>.</p> + +<p>Aqui vamos usar alguns truques comuns: fontes de harmonização, tamanho e bordas:</p> + +<pre class="brush:css;">input, textarea { + /* Para certificar-se que todos os campos de texto têm as mesmas configurações de fonte. Por padrão, textareas ter uma fonte monospace*/ + font: 1em sans-serif; + + /* Para dar o mesmo tamanho a todos os campo de texto */ + width: 300px; + -moz-box-sizing: border-box; + box-sizing: border-box; + + /* Para harmonizar o look & feel das bordas nos campos de texto*/ + border: 1px solid #999; +}</pre> + +<p>Formulários HTML suportam muitas pseudo-classes para descrever os estados de cada elemento. Como exemplo, vamos adicionar um pouco de destaque quando um campo está ativo. É uma maneira conveniente para ajudar a manter o controle do usuário de onde eles está no formulário.</p> + +<pre class="brush:css;">input:focus, textarea:focus { + /* Dar um pouco de destaque nos elementos ativos */ + border-color: #000; +}</pre> + +<p>Campos de texto de várias linhas precisam de alguns estilos personalizados sozinhos. Por padrão, um elemento {{HTMLElement ("textarea")}} é um bloco em linha com sua parte inferior alinhada à linha de base do texto. Na maioria das vezes, não é baseline o que queremos. Nesse caso, a fim de alinhar a <code><em>label </em></code>e o campo, temos que alterar a propriedade <em>vertical-align</em> do {{HTMLElement ("textarea")}} para <em>top</em>.</p> + +<p>Observe também o uso da propriedade de <em>resize</em>, que é uma forma de permitir que os usuários redimensionar um elemento {{HTMLElement ("textarea")}}.</p> + +<pre class="brush:css;">textarea { + /* Para alinhar corretamente os campos de texto de várias linhas com sua label*/ + vertical-align: top; + + /* Para dar espaço suficiente para digitar algum texto */ + height: 5em; + + /* Para permitir aos usuários redimensionarem qualquer textarea verticalmente. Ele não funciona em todos os browsers */ + resize: vertical; +}</pre> + +<p>Muitas vezes, os botões precisam de estilos especiais também. Para esse fim, nós o colocamos dentro de uma {{HTMLElement ("div")}} com uma classe css <em><code>button</code></em>. Aqui, queremos que o botão esteja alinhado com os outros campos . Para conseguir isso, temos de imitar a presença de uma {{HTMLElement ("label")}}. Isso é feito utilizando <code><em><strong>padding </strong></em></code>e <code><em><strong>margin</strong></em></code>.</p> + +<pre class="brush:css;">.button { + /* Para posicionar os botões para a mesma posição dos campos de texto */ + padding-left: 90px; /* mesmo tamanho que os elementos do tipo label */ +} +button { + /* Esta margem extra representa aproximadamente o mesmo espaço que o espaço entre as labels e os seus campos de texto*/ + margin-left: .5em; +}</pre> + +<p>Agora o nosso formulário parece muito mais bonito.</p> + +<p><img alt="" src="/files/4051/form-style.png" style="height: 260px; width: 900px;"></p> + +<h2 id="sect1"> </h2> + +<h2 id="Enviar_os_dados_para_seu_servidor_web">Enviar os dados para seu servidor web</h2> + +<p>A última parte, e talvez a mais complicado, é lidar com dados de formulário no lado do servidor. Como dissemos antes, na maioria das vezes, um formulário HTML é uma forma conveniente para perguntar ao usuário os dados e enviá-lo para um servidor web.</p> + +<p>O elemento {{HTMLElement("form")}} definirá onde e como enviar os dados, graças ao atribudo <em><strong>action</strong></em> e ao atributo <em><strong>method</strong></em></p> + +<p>Mas não é o suficiente. Nós também precisamos dar um nome a nossos dados. Esses nomes são importantes em ambos os lados; no lado do navegador, ele informa ao navegador que nome dar a cada pedaço de dados, e no lado do servidor, ele permite que o servidor lidar com cada pedaço de dados pelo nome.</p> + +<p>Então, para nomear seus dados, você precisará usar o atributo <em><strong><code>name </code></strong></em>em cada campo do formulário que irá recolher uma parte específica dos dados:</p> + +<pre class="brush:html;"><form action="/pagina-processa-dados-do-form" method="post"> + <div> + <label for="nome">Nome:</label> + <input type="text" id="nome" name="usuario_nome" /> + </div> + <div> + <label for="email">E-mail:</label> + <input type="email" id="email" name="usuario_email" /> + </div> + <div> + <label for="msg">Mensagem:</label> + <textarea id="msg" name="usuario_msg"></textarea> + </div> + + <div class="button"> + <button type="submit">Enviar sua mensagem</button> + </div> +</form></pre> + +<p>Em nosso exemplo, o formulário irá enviar 3 informações, chamados "usuario_nome", "usuario_email" e "usuario_msg" e os dados serão enviados para a URL "<em><strong>/pagina-processa-dados-do-form</strong></em>" com o método HTTP: <strong>POST </strong>.</p> + +<p>No lado do servidor, o script na URL "<em><strong>/pagina-processa-dados-do-form</strong></em>" receberá os dados como uma lista de itens 3 de chave/valor contidos na solicitação HTTP. A forma como o script vai lidar com esses dados fica a seu critério. Cada linguagem server-side (PHP, Python, Ruby, Java, C #, etc.) tem seu próprio mecanismo. Está além do escopo deste guia aprofundar o assunto, mas se você quiser saber mais, vamos dar alguns exemplos no artigo <a href="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data" title="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data"><span>Enviando e recuperando dados de formulário</span></a>.</p> + +<p> </p> + +<h2 id="Conclusão">Conclusão</h2> + +<p>Parabéns! Você construiu seu primeira formulário HTML. Aqui está um exemplo do resultado final.</p> + +<table style="height: 267px; width: 772px;"> + <thead> + <tr> + <th scope="col" style="text-align: center;">Live example</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ EmbedLiveSample('A_simple_form', '460', '240', '', 'Web/Guide/HTML/Forms/My_first_HTML_form/Example') }}</td> + </tr> + <tr> + </tr> + </tbody> +</table> + +<p>Agora é hora de dar uma olhada mais profunda. Formulários HTML são muito mais poderoso do que o que nós vimos aqui <a href="/pt-BR/docs/Web/Guide/HTML/Forms">e os outros artigos deste guia</a> irá ajudá-lo a dominar o resto.</p> |