From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../web/accessibility/aria/forms/alerts/index.html | 141 +++++++++++++++++++++ .../forms/dicas_b\303\241sicas_de_form/index.html" | 118 +++++++++++++++++ .../pt-br/web/accessibility/aria/forms/index.html | 21 +++ .../aria/forms/multipart_labels/index.html | 47 +++++++ 4 files changed, 327 insertions(+) create mode 100644 files/pt-br/web/accessibility/aria/forms/alerts/index.html create mode 100644 "files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" create mode 100644 files/pt-br/web/accessibility/aria/forms/index.html create mode 100644 files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html (limited to 'files/pt-br/web/accessibility/aria/forms') diff --git a/files/pt-br/web/accessibility/aria/forms/alerts/index.html b/files/pt-br/web/accessibility/aria/forms/alerts/index.html new file mode 100644 index 0000000000..b33525c5ad --- /dev/null +++ b/files/pt-br/web/accessibility/aria/forms/alerts/index.html @@ -0,0 +1,141 @@ +--- +title: Alerts +slug: Web/Accessibility/ARIA/forms/alerts +translation_of: Web/Accessibility/ARIA/forms/alerts +--- +

O problema

+ +

Você tem um formulário — um formulário de contato, por exemplo — no qual você deseja inserir algum that you want to put some accessible error checking into. Examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname.

+ +

O formulário

+ +

Primeiro, por favor leia sobre a técnica de aria-required  if you have not done so, as this technique expands upon that.

+ +

Here is a simple form:

+ +
 <form method="post" action="post.php">
+   <fieldset>
+     <legend>Please enter your contact details</legend>
+     <label for="name">Your name (required):</label>
+     <input name="name" id="name" aria-required="true"/>
+     <br />
+     <label for="email">E-Mail address (required):</label>
+     <input name="email" id="email" aria-required="true"/>
+     <br />
+     <label for="website">Website (optional):</label>
+     <input name="website" id="website"/>
+   </fieldset>
+   <label for="message">Please enter your message (required):</label>
+   <br />
+   <textarea name="message" id="message" rows="5" cols="80"
+             aria-required="true"></textarea>
+   <br />
+   <input type="submit" name="submit" value="Send message"/>
+   <input type="reset" name="reset" value="Reset form"/>
+ </form>
+
+ +

Checking for validity and notifying the user

+ +

Form validations consists of several steps:

+ +
    +
  1. Checking if the e-mail address or entered name are valid. Each field has a set of criteria which must be met in order to pass validation.  In order to simplify this example, we’ll check whether the e-mail address contains the “@” symbol, and if the name entry contains at least 1 character.
  2. +
  3. If the above criteria is not met, the field’s aria-invalid attribute will be given a value of “true”.
  4. +
  5. If the criteria was not met, the user will be notified via an alert. Instead of using the JavaScript ‘alert’ function, we’ll use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the “onblur” handler in JavaScript's default ‘alert’ function).
  6. +
+ +

Below is example JavaScript code which could be inserted above the closing “head” tag:

+ +
 <script type="application/javascript">
+ function removeOldAlert()
+ {
+   var oldAlert = document.getElementById("alert");
+   if (oldAlert){
+     document.body.removeChild(oldAlert);
+   }
+ }
+
+ function addAlert(aMsg)
+ {
+   removeOldAlert();
+   var newAlert = document.createElement("div");
+   newAlert.setAttribute("role", "alert");
+   newAlert.setAttribute("id", "alert");
+   var msg = document.createTextNode(aMsg);
+   newAlert.appendChild(msg);
+   document.body.appendChild(newAlert);
+ }
+
+ function checkValidity(aID, aSearchTerm, aMsg)
+ {
+   var elem = document.getElementById(aID);
+   var invalid = (elem.value.indexOf(aSearchTerm) < 0);
+   if (invalid) {
+     elem.setAttribute("aria-invalid", "true");
+     addAlert(aMsg);
+   } else {
+     elem.setAttribute("aria-invalid", "false");
+     removeOldAlert();
+   }
+ }
+ </script>
+
+ +

The checkValidity function

+ +

The primary method in JavaScript used for form validation is the checkValidity function. This method takes three parameters: The ID of the input that is to be validated, the term to search for to ensure validity, and the error message to be inserted into the alert.

+ +

To see if it is valid, the function checks whether the indexOf the input’s value is anything greater than -1. A value of -1 or less is returned if the index of the search term could not be found within the value.

+ +

If invalid, the function does two things:

+ +
    +
  1. It sets the element’s aria-invalid attribute to “true”, which will indicate to screen readers that there is invalid content in here.
  2. +
  3. It will call the addAlert function to add the alert with the provided error message.
  4. +
+ +

If the search term is found, the aria-invalid attribute is reset to “false”. In addition, any leftover alerts are removed.

+ +

The addAlert function

+ +

This function first removes any old alerts. The function is simple: It looks for an element with id “alert”, and if found, removes that from the document object model.

+ +

Next, the function creates a div element to hold the alert text. It gets an ID of “alert”. And it gets a role set of “alert”. This is actually ARIA-inspired, even though it doesn’t say “aria” in the attribute name. This is because that role is based on the XHTML Role Attribute Module that was simply ported to HTML for simplicity.

+ +

The text is added to the div element, and the div element is added to the document.

+ +

The moment this happens, Firefox will fire an “alert” event to assistive technologies when this div appears. Most screen readers will pick this one up automatically and speak it. This is similar to the Notification Bar in Firefox that prompts you whether you want to save a password. The alert we just created does not have any buttons to press, it just tells us what’s wrong.

+ +

Modifying the “onblur” event

+ +

All that’s left now is add the event handler. We need to change the two inputs for e-mail and name for this:

+ +
 <input name="name" id="name" aria-required="true"
+        onblur="checkValidity('name', ' ', 'Invalid name entered!');"/>
+ <br />
+ <input name="email" id="email" aria-required="true"
+        onblur="checkValidity('email', '@', 'Invalid e-mail address');"/>
+
+ +

Testing the example

+ +

If you use Firefox 3 and a currently-supported screen reader, try the following:

+ +
    +
  1. Enter only your first name as the name. When tabbing, you’ll hear an alert that tells you you’ve entered an invalid name. You can then shift-tab back and correct the error.
  2. +
  3. Enter an e-mail address without the “@” symbol. When tabbing out of this field, you should hear a warning that says you didn’t enter a valid e-mail address.
  4. +
+ +

In both cases, when returning focus to the field in question, your screen reader should tell you that this field is invalid. JAWS 9 supports this, but JAWS 8 does not, so this may not work in all versions of the screen readers supported.

+ +

A few questions that you might have

+ +
+
Q. Why did you put both “(required)” in the label text and the aria-required attribute on some of the inputs?
+
A. If this were a real live form, and the site was being visited by a browser that does not yet support ARIA, we’d still want to give an indication that this is a required field.
+
Q. Why don’t you set focus back to the invalid field automatically?
+
A. Because this is not allowed by the Windows API specs, and possibly others. Also, letting the focus jump around without real user interaction too often is not a nice thing to do in general. 
+
+ +
TBD: let's rethink this -- personally, I think setting focus might be good if done without causing a keyboard trap.
diff --git "a/files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" "b/files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" new file mode 100644 index 0000000000..722c60d420 --- /dev/null +++ "b/files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" @@ -0,0 +1,118 @@ +--- +title: Dicas básicas de form +slug: Web/Accessibility/ARIA/forms/Dicas_básicas_de_form +translation_of: Web/Accessibility/ARIA/forms/Basic_form_hints +--- +
+

Form labels

+
+ +

Quando estiver implementando forms usando elementos HTML tradicionais relacionados à foms, é importante fornecer labels para controles e para explicitamente associar um label com o seu ocntrole. Quando um usuário de leitor de tela navega uma página, o leitor de tel irá descrever os controles do form, mas sem uma associação direta entre o controle e seu label, o leitor de tela não tem maneira de saber qual label é o correto.

+ +

O exemplo abaixo mostra um form simples com labels. Note que cada elemento {{HTMLElement("input")}} tem um id, e cada elemento {{HTMLElement("label")}} tem um atributo for indicando o id do {{HTMLElement("input")}} associado.

+ +

Exempl0 1. Form simples com labels

+ +
<form>
+  <ul>
+    <li>
+      <input id="wine-1" type="checkbox" value="riesling"/>
+      <label for="wine-1">Berg Rottland Riesling</label>
+    </li>
+    <li>
+      <input id="wine-2" type="checkbox" value="weissbergunder"/>
+      <label for="wine-2">Weissbergunder</label>
+    </li>
+    <li>
+      <input id="wine-3" type="checkbox" value="pinot-grigio"/>
+      <label for="wine-3">Pinot Grigio</label>
+    </li>
+    <li>
+      <input id="wine-4" type="checkbox" value="gewurztraminer"/>
+      <label for="wine-4">Berg Rottland Riesling</label>
+    </li>
+  </ul>
+</form>
+
+ +

Rotulando com ARIA

+ +

O elemento HTML {{HTMLElement("label")}} é apropriado para elementos relacionados com form, mas muitos controles de form são implementados como widget JavaScript dinâmico, usando {{HTMLElement("div")}}s ou {{HTMLElement("span")}}s. WAI-ARIA, a especificação de Aplicações Internet Ricas em Acessibilidade da W3C Iniciativa de Acessibilidade Web, fornece o atributo aria-labelledby para esses casos.

+ +

O exemplo abaixo mostra um grupo de botões rádio usando um lista não ordenada. Note que na linha 3, o elemento {{HTMLElement("li")}} seta o atributo aria-labelledby para "rg1_label," o id do elemento {{HTMLElement("h3")}} na linha 1, que é o label para o grupo rádio.

+ +

Exemplo 2. Um grupo rádio implementado usando uma lista não ordenada (adaptado de http://www.oaa-accessibility.org/examplep/radio1/)

+ +
<h3 id="rg1_label">Lunch Options</h3>
+
+<ul class="radiogroup" id="rg1"  role="radiogroup" aria-labelledby="rg1_label">
+  <li id="r1"  tabindex="-1" role="radio" aria-checked="false">
+    <img role="presentation" src="radio-unchecked.gif" /> Thai
+  </li>
+  <li id="r2"  tabindex="-1" role="radio"  aria-checked="false">
+    <img role="presentation" src="radio-unchecked.gif" /> Subway
+  </li>
+  <li id="r3"   tabindex="0" role="radio" aria-checked="true">
+    <img role="presentation" src="radio-checked.gif" /> Radio Maria
+  </li>
+</ul>
+
+ +

Descrevendo com ARIA

+ +

Controles form às vezes tem uma descrição associada com eles, em adição ao label. ARIA fornece o atributo aria-describedby para diretamente associar a descrição com o controle.

+ +

O exemplo abaixo mostra um elemento {{HTMLElement("button")}} que é descrito por uma sentença num elemento {{HTMLElement("div")}} separado. O atributo aria-describedby no {{HTMLElement("button")}} referencia o id de {{HTMLElement("div")}}.

+ +

Exemplo 3. Um botão descrito por um elemento separado.

+ +
<button aria-describedby="descriptionRevert">Revert</button>
+<div id="descriptionRevert">Reverting will undo any changes that have been made since the last save.</div>
+ +

(Note que o atributo aria-describedby é usado para outros propósitos, além de controles do form.)

+ +

Campos inválidos e obrigatórios

+ +

Web developers tipicamente usam estratégias de apresentação para indicar campos obrigatórios ou campos inválidos, mas tecnologias assistivas (TAs) não podem necessariamente inferir essa informação a partir da apresentação. ARIA fornece atributos para indicar que os controles do form são obrigatórios ou inválidos:

+ + + +

O exemplo abaixo mostra um form simples com três campos. Nas linhas 4 e 12, o atributo aria-required é setado para true (em adição aos asteriscos próximos aos labels) indicando que os campos de nome e e-mail são obrigatórios. A segunda parte do exemplo é um trecho de JavaScript que valida o e-mail e seta o atributo aria-invalid do campo e-mail (linha 12 do HTML) de acordo com o resultado (em adição à mudança de apresentação do elemento).

+ +

Exemplo 4a. Um form com campos obrigatórios.

+ +
<form>
+  <div>
+    <label for="name">* Name:</label>
+    <input type="text" value="name" id="name" aria-required="true"/>
+  </div>
+  <div>
+    <label for="phone">Phone:</label>
+    <input type="text" value="phone" id="phone" aria-required="false"/>
+  </div>
+  <div>
+    <label for="email">* E-mail:</label>
+    <input type="text" value="email" id="email" aria-required="true"/>
+  </div>
+</form>
+ +

Exemplo 4b. Parte de um script que valida a entrada no form.

+ +
var validate = function () {
+  var emailElement = document.getElementById(emailFieldId);
+  var valid = emailValid(formData.email); // returns true if valid, false otherwise
+
+  emailElement.setAttribute("aria-invalid", !valid);
+  setElementBorderColour(emailElement, valid); // sets the border to red if second arg is false
+};
+ +

Fornecendo Mensagens de Erro Úteis

+ +

Leia como usar alertas ARIA para melhorar forms.

+ +
A ser decidido: devemos ou combinar em um artigo ou separar em técnicas, ou ambos. Além disso, é ARIA marcação apropriada para mensagens de erro em uma página carregada após a validação do lado do servidor?
+ +

Para maiores informações usando ARIA para acessibilidade de forms, veja o documento Práticas de Cricação de WAI-ARIA.

diff --git a/files/pt-br/web/accessibility/aria/forms/index.html b/files/pt-br/web/accessibility/aria/forms/index.html new file mode 100644 index 0000000000..355c70b673 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/forms/index.html @@ -0,0 +1,21 @@ +--- +title: Formulários +slug: Web/Accessibility/ARIA/forms +tags: + - ARIA + - Accessibility + - Acessibilidade + - Rótulos + - WebMechanics + - formulários +translation_of: Web/Accessibility/ARIA/forms +--- +

As páginas a seguir fornecem várias técnicas para melhorar a acessibilidade nos formulários web:

+ + + +

Ver também o Artigo do Yahoo! sobre validação de formulário e ARIA, cobrindo muito do mesmo conteúdo.

diff --git a/files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html b/files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html new file mode 100644 index 0000000000..102274fadb --- /dev/null +++ b/files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html @@ -0,0 +1,47 @@ +--- +title: Usando ARIA para rótulos com campos incorporados - Multipart labels +slug: Web/Accessibility/ARIA/forms/Multipart_labels +tags: + - ARIA + - Accessibility + - Acessibilidade + - Formulários+ARIA + - Guía + - Intermediário + - PrecisaDeConteúdo +translation_of: Web/Accessibility/ARIA/forms/Multipart_labels +--- +
+

O problema

+ +

Você tem um formulário onde existe uma pergunta simples e a resposta é mencionada na própria questão. Um exemplo clássico, que todos nós conhecemos das configurações de nossos navegadores, é a colocação "Deletar o histórico após x dias".  "Apagar o histórico após" está à esquerda da caixa de texto, x é o número, por exemplo, 21 e a palavra "dias" vem depois dessa caixa, formando uma sentença de fácil compreensão.

+ +

Se você está usando um leitor de tela tem que perceber que, quando vai para esta configuração no Firefox, escuta a pergunta "Deletar o histórico depois de 21 dias?", seguida por um aviso de que você está em uma caixa de texto contendo o número 21. Isso não é legal? Você não precisa navegar ao redor para descobrir a unidade. "Dias" pode, facilmente, ser "meses", ou "anos" em muitos diálogos comuns, não havendo maneira de descobrir, a não ser com comandos para reexaminar a tela.

+ +

A solução está em um atributo ARIA chamado aria-labelledby (aria-etiqueta liderada por). Seu parâmetro é uma cadeia de caracteres (string) que consiste de IDs dos elementos HTML que você quer concatenar em um único nome acessível.

+ +

Tanto o atributo aria-labelledby, como o aria-describedby (aria-descrito por), são especificados no elemento de formulário que será rotulado, por exemplo uma <input>. Em ambas as situações, as ligações do controle da rotulagem for/label, que podem, também, estar presentes, serão substituídas pelo atributo aria-labelledby. Se você oferecer o atributo aria-labelledby em uma página HTML, então deve, da mesma forma, providenciar uma arquitetura de rótulo que vá, igualmente, apoiar os navegadores mais antigos, que ainda não têm suporte ARIA. Com Firefox 3, seus utilizadores cegos conseguem, automaticamente, melhor acessibilidade com o novo atributo, mas quem utiliza navegadores antigos não sofrerá abandono no escuro, desta forma.

+ +

Exemplo:

+Desligar o computador após  minutos + +
<input aria-labelledby="labelShutdown shutdownTime shutdownUnit" type="checkbox" />
+<span id="labelShutdown">Shut down computer after</span>
+<input aria-labelledby="labelShutdown shutdownTime shutdownUnit" id="shutdownTime" type="text" value="10" />
+<span id="shutdownUnit"> minutes</span>
+
+ +

Uma nota para quem usa  JAWS 8

+ +

O JAWS 8.0 tem a sua própria lógica para encontrar os labels e isso o faz, sempre, substituir a caixa de texto com o accessibleName que uma página HTML recebe. Quanto ao JAWS 8, eu ainda não encontrei uma maneira de fazê-lo aceitar o label do exemplo acima. Mas o NVDA e o Window-Eyes fazem isso muito bem e a Orca, no Linux, também não apresenta problemas.  (Os autores do artigo, são: bunnybooboo, kscarfone, StephenKelly, Kritz, Fredchat, Sheppy, Aaronlev)

+ +
TBD: adicione mais informação de compatibilidade
+ +

Isto pode ser executado sem ARIA?

+ +

O membro da comunidade Ben Millard apontou, numa publicação em um blogue, que os controles podem ser embutidos nos labels, como mostrado no exemplo acima, usando HTML 4, controls can be embedded in labels as shown in the above example using HTML 4, simplesmente com a incorporação da entrada (input) no rótulo (label). Agradecemos pela informação, Ben! É muito útil e deixa claro que algumas técnicas que estão disponíveis há anos escapam, às vezes, até mesmo aos gurus. Esta técnica funciona em Firefox; entretanto, isso não é verdade para muitos outros navegadores, inclusive IE. Para labels com controles de formulários embutidos o uso do atributo aria-labelledby ainda é a melhor abordagem.

+ +

 

+
+ +

 

-- cgit v1.2.3-54-g00ecf