Web Accessibility Check – Errors and Warnings

How to Check Accessibility of Website

Checking a website for accessibility means ensuring that everyone, including people with disabilities, can use your website or app. This involves testing your content against guidelines like WCAG, which outline how to make digital experiences more inclusive. Using Aspose.HTML for Java, you can automate this process by scanning HTML and CSS for accessibility issues – either against the full WCAG set of standards or by focusing on specific criteria.

In this article, you will learn how to assess website accessibility for WCAG compliance using the classes and methods from the com.aspose.html.accessibility and com.aspose.html.accessibility.results packages. We will explore various classes and interfaces that help collect error and warning information while checking a website’s accessibility. Special attention will be given to the failure criteria and methods for reporting errors, along with a Java example that demonstrates how to retrieve web accessibility errors after validating an HTML document.

Let’s see a code snippet related to web accessibility validation. The following code checks the accessibility of a remote HTML page using all WCAG validation rules and prints details of any rules that were not successfully met:

  1. Use the WebAccessibility() constructor to create an instance of the WebAccessibility class responsible for web accessibility validation.
  2. Call the createValidator() method to create a validator object.
  3. Load an HTML page using the HTMLDocument(Url) constructor.
  4. Use the validate(document) method to check the web page for accessibility. The result is stored in the validationResult variable.
  5. Check whether the validation was successful. For each accessibility issue, print information about the rule code, rule description, and whether the validation succeeded or failed.
 1// Initialize webAccessibility container
 2WebAccessibility webAccessibility = new WebAccessibility();
 3
 4// Create an accessibility validator with static instance
 5// for all rules from repository that match the builder settings
 6AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
 7
 8// Initialize an HTMLDocument object
 9final HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/generators/video/");
10ValidationResult validationResult = validator.validate(document);
11
12// Checking for success
13if (!validationResult.getSuccess()) {
14    // Get a list of Details
15    for (RuleValidationResult detail : validationResult.getDetails()) {
16        System.out.println(String.format("%s: %s = %s",
17                detail.getRule().getCode(),
18                detail.getRule().getDescription(),
19                detail.getSuccess()
20        ));
21    }
22}
Example_ValidateWebsite hosted with ❤ by GitHub

Errors and Warnings

Detecting errors helps identify barriers that may prevent people with disabilities from using and interacting with web content effectively. Errors and warnings guide what must be addressed to improve web accessibility. They serve as a roadmap for developers and designers to make necessary changes.

IError

The IError is a public interface containing information about the validation error. This means an erroneous check, i.e., the rule was not passed – and its result does not match Accessibility.

The IError interface describes the details of a validation problem encountered during accessibility checks. It provides key information about the error, including a human-readable message via getErrorMessage(), the result status with getSuccess(), and the error type as a numeric value (getErrorType()) and a descriptive name (getErrorTypeName()), such as Error or Warning. Additionally, getTarget() returns the specific HTML or CSS element in which the problem was encountered, allowing accessibility issues to be accurately identified and corrected. This interface is essential for effectively interpreting and reporting accessibility check results.

IError object has such meanings:

* ErrorType = 1 and Success = false – this means that the error is critical, and the result of the check is not performed.
* ErrorType = 2 and Success = true – this means that the error is not critical but has an informational character and displays hints for possible improvement. 

The type of error is determined by the type of technique:

Target

The Target class represents a specific HTML or CSS element where an accessibility error or warning was detected during validation. It provides two key properties: Item, which returns the actual object (such as an HTML tag or CSS rule) that caused the problem, and TargetType, which determines whether the source of the problem is an HTML element or a CSS component.

TargetTypes

The TargetTypes enumeration defines the possible types of objects in an HTML document where an accessibility error or warning might be found. It helps classify the source of the problem, making it easier to identify and resolve. The enumeration includes three values:

NameValueDescription
HTMLElement0The element containing the HTMLElement from a document: standard HTML elements such as <img> or <button>.
CSSStyleRule1The element containing the CSSStyleRule from a document: specific CSS rules in stylesheets.
CSSStyleSheet2The element containing the CSSStyleSheet from a document: entire CSS stylesheets.

This enumeration works in conjunction with the Target class to indicate exactly what type of element caused the validation result.

Generate Full Accessibility Report

Let’s look at the Java code for iterating through the web accessibility check results, paying particular attention to the failure criteria and the details of the methods that report errors. Example of getting errors details and elements of an HTML document:

  1. Use the RuleValidationResult class and iterate through the ruleResult objects contained within validationResult.getDetails(). These represent different accessibility criteria.
  2. Print the code and description of the criterion and whether it was successful or not. For this, use the Code and Description properties of the IRule interface.
  3. Use the getSuccess() method to check the criteria.
  4. Use the ITechniqueResult objects – ruleDetail contained within ruleResult.getErrors(). The ITechniqueResult objects represent individual rule results for the criterion that reported errors.
  5. Print the information about the method, including the method code, success status, and description.
  6. Use the IError property to obtain the error object from the ruleDetail. The ruleDetail represents a specific accessibility issue, and the error object contains information about that issue.
  7. Use getTarget() to retrieve the target object associated with the error. The target object typically represents the specific HTML element, CSS rule, or other content that triggered the accessibility error.
  8. Print information about the error. It includes the error type error.getErrorTypeName() and the error message error.getErrorMessage().
  9. Use the getTargetType() method of the Target class to check the type of the target object. Depending on the type of the target object, specific information is extracted and printed to the console.
 1// Initialize a webAccessibility container
 2WebAccessibility webAccessibility = new WebAccessibility();
 3
 4// Create an accessibility validator with static instance
 5// for all rules from repository that match the builder settings
 6AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
 7
 8String documentPath = "input.html";
 9
10// Initialize an object of the HTMLDocument class
11final HTMLDocument document = new HTMLDocument(documentPath);
12ValidationResult validationResult = validator.validate(document);
13
14for (RuleValidationResult ruleResult : validationResult.getDetails()) {
15    //  list only unsuccessful rule
16    if (!ruleResult.getSuccess()) {
17        // print the code and description of the rule
18        System.out.println(String.format("%s: %s = %s",
19                ruleResult.getRule().getCode(),
20                ruleResult.getRule().getDescription(),
21                ruleResult.getSuccess()
22        ));
23
24        // print the results of methods with errors
25        for (ITechniqueResult ruleDetail : ruleResult.getErrors()) {
26            // print the code and description of the method
27            StringBuilder str = new StringBuilder(String.format("\n{0}: {1} - {2}",
28                    ruleDetail.getRule().getCode(),
29                    ruleDetail.getSuccess(),
30                    ruleDetail.getRule().getDescription()
31            ));
32            // get an error object
33            IError error = ruleDetail.getError();
34            // get a target object
35            Target target = error.getTarget();
36            // get error type and message
37            str.append(String.format("\n\n\t%s : %s",
38                    error.getErrorTypeName(),
39                    error.getErrorMessage()
40            ));
41
42            if (target != null) {
43                // Checking the type of the contained object for casting and working with it
44                if (target.getTargetType() == TargetTypes.CSSStyleRule) {
45                    ICSSStyleRule cssRule = (ICSSStyleRule) target.getItem();
46                    str.append(String.format("\n\n\t%s",
47                            cssRule.getCSSText()
48                    ));
49                }
50                if (ruleDetail.getError().getTarget().getTargetType() == TargetTypes.CSSStyleSheet) {
51                    str.append(String.format("\n\n\t%s",
52                            ((ICSSStyleSheet) target.getItem()).getTitle()
53                    ));
54                }
55                if (ruleDetail.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
56                    str.append(String.format("\n\n\t%s",
57                            ((HTMLElement) target.getItem()).getOuterHTML()
58                    ));
59                }
60            }
61            System.out.println(str);
62        }
63    }
64}
Example_Errors hosted with ❤ by GitHub

For each failed criterion, the code lists rule descriptions, failed methods, error messages, and highlights the exact HTML or CSS element where the issue was found. This approach is ideal for generating a complete and accurate accessibility report, including error context and technical diagnostics for developers.

See Also

  • You will find helpful tips on evaluating and improving text visibility in the article Color Contrast Accessibility, which covers contrast checking based on WCAG using Aspose.HTML for Java.
  • For instructions on checking web content is compatible with screen readers, you will find in the article Screen Reader Accessibility. You will learn how to check alt text and other key elements.
  • If you want to learn how to view validation results and identify web accessibility issues, see the Validation Results article.

Aspose.HTML offers a free online Color Contrast Checker to check the contrast ratios in your web designs. This tool provides feedback on whether your color choices meet accessibility standards.

Text “Color Contrast Checker”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.