JAVA SCRIPT - Highlighting Errors Accessibly - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Highlighting Errors Accessibly - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, December 31, 2018

JAVA SCRIPT - Highlighting Errors Accessibly

 Highlighting Errors Accessibly


Problem

You want to highlight form field entries that have incorrect data, and you want to ensure the highlighting is effective for all web page users.

Solution

Use CSS to highlight the incorrectly entered form field, and use WAI-ARIA (Accessible Rich Internet Applications) markup to ensure the highlighting is apparent to all users:


[aria-invalid] {
 background-color: #ffeeee;
}

For the fields that need to be validated, assign a function to the form field’s onchange event handler that checks whether the field value is valid. If the value is invalid, pop up an alert with information about the error at the same time that you highlight the field:

document.getElementById("elemid").onchange=validateField;
...
function validateField() {
 // check for number
 if (isNaN(this.value)) {
 this.setAttribute("aria-invalid, "true");
 generateAlert("You entered an invalid value for A. Only numeric values
 such as 105 or 3.54 are allowed");
 }
}

For the fields that need a required value, assign a function to the field’s onblur event handler that checks whether a value has been entered:

document.getElementById("field").onblur=checkMandator;
...
function checkMandatory() {
 // check for data
 if (this.value.length == 0) {
 this.setAttribute("aria-invalid", "true");
 generateAlert("A value is required in this field");
 }
}

If any of the validation checks are performed as part of the form submission, make sure to cancel the submission event if the validation fails.

EXPLAIN

The WAI-ARIA (Accessible Rich Internet Applications) provides a way of marking cer‐ tain fields and behaviors in such a way that assistive devices do whatever is the equivalent behavior for people who need these devices. 

If a person is using a screen reader, setting the aria-attribute attribute to true (or adding it to the element) should trigger a visual warning in the screen reader—comparable to a color indicator doing the same for people who aren’t using assistive technologies. 

In addition, the role attribute can be set to several values of which one, “alert”, triggers a comparable behavior in screen readers (typically saying out the field contents). Providing these cues are essential when you’re validating form elements. 

You can vali‐ date a form before submission and provide a text description of everything that’s wrong. A better approach, though, is to validate data for each field as the user finishes, so they’re not left with a lot of irritating error messages at the end. 

As you validate the field, you can ensure your users know exactly which field has failed by using a visual indicator. They shouldn’t be the only method used to mark an error, but they are an extra courtesy. If you highlight an incorrect form field entry with colors, avoid those that are hard to differentiate from the background. 

If the form background is white, and you use a dark yellow, gray, red, blue, green, or other color, there’s enough contrast that it doesn’t matter if the person viewing the page is color blind or not. In the example, I used a darker pink in the form field. I could have set the color directly, but it makes more sense to handle both updates— setting aria-invalid and changing the color—with one CSS setting. 

Luckily, CSS at‐ tribute selectors simplify our task in this regard. In addition to using color, you also need to provide a text description of the error, so there’s no question in the user’s mind about what the problem is. How you display the information is also an important consideration. None of us really like to use alert boxes, if we can avoid them. 

Alert boxes can obscure the form, and the only way to access the form element is to dismiss the alert with its error message. A better approach is to embed the information in the page, near the form. We also want to ensure the error message is available to people who are using assistive technologies,

such as a screen reader. This is easily accomplished by assigning an ARIA alert role to the element containing the alert for those using screen readers or other AT devices. One final bonus to using aria-invalid is it can be used to discover all incorrect fields when the form is submitted. Just search on all elements where the attribute is present and if any are discovered, you know there’s still an invalid form field value that needs correcting. 

Demonstrates how to highlight an invalid entry on one of the form ele‐ ments, and highlight missing data in another. The example also traps the form submit, and checks whether there are any invalid form field flags still set. Only if everything is clear is the form submission allowed to proceed.

Providing visual and other cues when validating form fields 


<head>
<title>Validating Forms</title>
<style>
[aria-invalid] {
 background-color: #ffeeee;
}
[role="alert"]
{
 background-color: #ffcccc;
 font-weight: bold;
 padding: 5px;
 border: 1px dashed #000;
}
div
{
 margin: 10px 0;
 padding: 5px;
 width: 400px;
 background-color: #ffffff;
}
</style>
</head>
<body>
<form id="testform">
 <div>
<label for="firstfield">*First Field:</label>

 <input aria-required="true" id="firstfield" name="firstfield" required="" type="text" />
 </div>
<div>
<label for="secondfield">Second Field:</label>

 <input id="secondfield" name="secondfield" type="text" />
 </div>
<div>
<label for="thirdfield">Third Field (numeric):</label>

<input id="thirdfield" name="thirdfield" type="text" />
 </div>
<div>
<label for="fourthfield">Fourth Field:</label>

 <input id="fourthfield" name="fourthfield" type="text" />
 </div>
<input type="submit" value="Send Data" />
</form>
<script>
 document.getElementById("thirdfield").onchange=validateField;
 document.getElementById("firstfield").onblur=mandatoryField;
 document.getElementById("testform").onsubmit=finalCheck;
 function removeAlert() {
 var msg = document.getElementById("msg");
 if (msg) {
 document.body.removeChild(msg);
 }
 }
 function resetField(elem) {
 elem.parentNode.setAttribute("style","background-color: #ffffff");
 var valid = elem.getAttribute("aria-invalid");
 if (valid) elem.removeAttribute("aria-invalid");
 }
 function badField(elem) {
 elem.parentNode.setAttribute("style", "background-color: #ffeeee");
 elem.setAttribute("aria-invalid","true");
 }
 function generateAlert(txt) {
 // create new text and div elements and set
 // Aria and class values and id
 var txtNd = document.createTextNode(txt);
 msg = document.createElement("div");
 msg.setAttribute("role","alert");
 msg.setAttribute("id","msg");
 msg.setAttribute("class","alert");
 // append text to div, div to document
 msg.appendChild(txtNd);
 document.body.appendChild(msg);
 }
 function validateField() {
 // remove any existing alert regardless of value
removeAlert();
 // check for number
 if (!isNaN(this.value)) {
 resetField(this);
 } else {
 badField(this);
 generateAlert("You entered an invalid value in Third Field. " +
 "Only numeric values such as 105 or 3.54 are allowed");
 }
 }
 function mandatoryField() {
 // remove any existing alert
 removeAlert();
 // check for value
 if (this.value.length > 0) {
 resetField(this);
 } else {
 badField(this);
 generateAlert("You must enter a value into First Field");
 }
 }
 function finalCheck() {
 removeAlert();
 var fields = document.querySelectorAll("[aria-invalid='true']");
 if (fields.length > 0) {
 generateAlert("You have incorrect fields entries that must be fixed " +
 "before you can submit this form");
 return false;
 }
 }
</script>
</body>

If either of the validated fields is incorrect in the application, the aria-invalid attribute is set to true in the field, and an ARIA role is set to alert on the error message, as shown in Figure 6-8. When the error is corrected, the aria-invalid attribute is re‐ moved, as is the alert message. Both have the effect of changing the background color for the form field.

Notice in the code that the element wrapping the targeted form field is set to its correct state when the data entered is correct, so that when a field is corrected it doesn’t show up as inaccurate or missing on the next go-round.

I remove the existing message alert regardless of the previous event, as it’s no longer valid with the new event. When the form is submitted, the application uses the querySelectorAll() method call to check for all instances of aria-invalid set to true, and rejects the submission until these are corrected.


var badFields = document.querySelectorAll("[aria-invalid='true']");

You can also disable or even hide the correctly entered form elements, as a way to accentuate those with incorrect or missing data. However, I don’t recommend this ap‐ proach. Your users may find as they fill in the missing information that their answers in other fields are incorrect. If you make it difficult for them to correct the fields, they’re not going to be happy with the experience—or the company, person, or organization providing the form.

Another approach you can take is to only do validation when the form is submitted. Many built-in libraries operate this way. Rather than check each field for mandatory or correct values as your users tab through, you only apply the validation rules when the form is submitted. This allows users who want to fill out the form in a different order to do so without getting irritating validation messages as they tab through.

This ap‐ proach is a friendlier technique for those people using a keyboard, rather than a mouse, to tab through the form. Or you can use a mix of both: field-level validation for correct data type and format, form-level validation for required values. Using JavaScript to highlight a form field with incorrect and missing data is only one part of the form submission process.

You’ll also have to account for JavaScript being turned off, which means you have to provide the same level of feedback when processing the form information on the server, and providing the result on a separate page. It’s also important to mark if a form field is required ahead of time.

Use an asterisk in the form field label, with a note that all form fields with an asterisk are required. Use the aria-required attribute to ensure this information is communicated to those using assistive devices. I also recommend using the HTML5 required attribute when using aria-required.


No comments:

Post a Comment

Post Top Ad