Accessibility Validation Results in Java

After AccessibilityValidator.validate() checks an HTMLDocument, use ValidationResult to read the overall status, inspect rule and technique details, and serialize reported issues as text, JSON, or XML.

Aspose.HTML for Java provides the com.aspose.html.accessibility API for automated checks based on WCAG 2.0 rules. This article explains how to inspect the returned results and save them for reporting. For validator creation and rule selection, see Accessibility Validator – Website Accessibility Check in Java.

ValidationResult Class

The com.aspose.html.accessibility.results package contains classes that describe accessibility rule validation results. ValidationResult is the top-level result returned for the selected validation scope.

MethodWhat it returns or does
getSuccess()Returns the overall validation status.
getDetails()Returns rule-level RuleValidationResult objects.
saveToString()Serializes the validation result to a Java String.
saveTo(writer, format)Writes the result in the selected text, JSON, or XML format.

The following example validates a local HTML document with all available rules and prints rule-level results when the overall check is unsuccessful:

  1. Create a WebAccessibility instance.
  2. Create an AccessibilityValidator with ValidationBuilder.getAll().
  3. Load the source HTML file into an HTMLDocument.
  4. Call validate(document) to obtain a ValidationResult.
  5. If getSuccess() returns false, iterate through getDetails() and print each checked rule and its status.
 1// Validate HTML against WCAG rules using Java
 2
 3// Create a WebAccessibility instance
 4WebAccessibility webAccessibility = new WebAccessibility();
 5
 6// Create an accessibility validator with static instance for all rules
 7// from repository that match the builder settings
 8AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
 9
10// Prepare a path to a source HTML file
11String documentPath = "input.html";
12
13// Initialize an object of the HTMLDocument class
14final HTMLDocument document = new HTMLDocument(documentPath);
15ValidationResult validationResult = validator.validate(document);
16
17// Checking for success
18if (!validationResult.getSuccess()) {
19    // Get a list of RuleValidationResult Details
20    for (RuleValidationResult detail : validationResult.getDetails()) {
21        System.out.println(String.format("%s: %s = %s",
22                detail.getRule().getCode(),
23                detail.getRule().getDescription(),
24                detail.getSuccess()));
25    }
26}

RuleValidationResult Class

The RuleValidationResult class represents the result of checking one accessibility rule. It includes the checked rule, its status, and a collection of ITechniqueResult objects that describe individual technique checks.

The main methods are:

The following fragment iterates through the RuleValidationResult objects returned by validationResult.getDetails():

1    // Get a list of RuleValidationResult Details
2    for (RuleValidationResult result : validationResult.getDetails())
3    {
4        System.out.println(String.format("%s: %s = %s",
5            result.getRule().getCode(), result.getRule().getDescription(), result.getSuccess()));
6    }

If the details contain results for H37 and H67, the output follows this pattern:

1H37: Check alt attributes for images = true
2H67: Check that all forms have labels = false

ITechniqueResult

The ITechniqueResult interface describes one technique validation result. Use getRule() to identify the checked technique, getSuccess() to read its status, and getError() to access the associated IError when an issue is reported.

The following example drills down from unsuccessful rule results to their technique results:

  1. Iterate through the rule results returned by validationResult.getDetails().
  2. Select each RuleValidationResult for which getSuccess() returns false.
  3. Print the failed rule code and description.
  4. Iterate through getResults() and print the code, status, and description of each technique checked for that rule.
 1// Validate HTML accessibility using Java and get detailed failed rule results
 2
 3// Create a WebAccessibility instance
 4WebAccessibility webAccessibility = new WebAccessibility();
 5
 6// Create an accessibility validator with static instance for all rules
 7// from repository that match the builder settings
 8AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
 9
10String documentPath = "input.html";
11
12// Initialize an object of the HTMLDocument class
13final HTMLDocument document = new HTMLDocument(documentPath);
14ValidationResult validationResult = validator.validate(document);
15
16// Take a list of rules results
17for (RuleValidationResult ruleResult : validationResult.getDetails()) {
18    // List only unsuccessful rule
19    if (!ruleResult.getSuccess()) {
20        // Print the code and description of the rule
21        System.out.println(String.format("%s: %s",
22                ruleResult.getRule().getCode(),
23                ruleResult.getRule().getDescription()
24        ));
25
26        // Print the results of all methods
27        for (ITechniqueResult ruleDetail : ruleResult.getResults()) {
28            // Print the code, status, and description of each technique
29            StringBuilder str = new StringBuilder(String.format("%n%s: %s - %s",
30                    ruleDetail.getRule().getCode(),
31                    ruleDetail.getSuccess(),
32                    ruleDetail.getRule().getDescription()
33            ));
34            System.out.println(str);
35        }
36    }
37}

Save Validation Results

After validation, you can serialize the result for logs, reports, or downstream processing. Use ValidationResultSaveFormat with saveTo(writer, format) to select the output format.

Three main formats are available for saving web accessibility validation results:

Save Validation Results to a String

Use saveToString() when you need the text representation directly as a Java String:

  1. Load the HTML document and create an accessibility validator.
  2. Call validate(document) to obtain a ValidationResult.
  3. Call saveToString() to serialize the result as text.
  4. Send the returned string to the console, a log, or another reporting workflow.
 1// Validate HTML for accessibility in Java and export all errors and warnings as a string
 2
 3String htmlPath = "input.html";
 4
 5final HTMLDocument document = new HTMLDocument(htmlPath);
 6AccessibilityValidator validator = new WebAccessibility().createValidator();
 7ValidationResult validationresult = validator.validate(document);
 8
 9// get rules errors in string format
10String content = validationresult.saveToString();
11
12// SaveToString - return only errors and warnings
13// if everything is ok, it will return "validationResult:true"
14System.out.println(content);

The text starts with the overall validation status and then lists reported errors and warnings. The exact entries depend on the input document, selected rules, and library version:

 1validationResult:False;
 2%%
 3technique: H35;
 4criterion: 1.1.1;
 5type: Error;
 6description: Check that the applet element contains an alt attribute with a text alternative for the applet. ;
 7source: <applet code="tictactoe.class" width="250" height="250">tic-tac-toe game</applet>;
 8%%
 9technique: H37;
10criterion: 1.1.1;
11type: Error;
12description: Img element missing an alt attribute. The value of this attribute is referred to as "alt text".;
13source: <img src="image1.jpeg">;
14%%
15
16...

The serialized fields shown above mean:

Save Validation Results in XML Format

Use XML when the report must be parsed by another tool or included in an automated workflow:

  1. Validate the source HTMLDocument and obtain a ValidationResult.
  2. Create a writer for the serialized output.
  3. Call saveTo(writer, ValidationResultSaveFormat.XML).
  4. Read or parse the resulting XML string as required by the application.
 1// Validate HTML for accessibility in Java and export all errors and warnings as an XML
 2
 3String htmlPath = "input.html";
 4
 5final HTMLDocument document = new HTMLDocument(htmlPath);
 6AccessibilityValidator validator = new WebAccessibility().createValidator();
 7ValidationResult validationresult = validator.validate(document);
 8
 9final java.io.StringWriter sw = new java.io.StringWriter();
10validationresult.saveTo(sw, ValidationResultSaveFormat.XML);
11
12String xml = sw.toString();
13System.out.println(xml);
14
15DocumentBuilderFactory documentBuildFactory = DocumentBuilderFactory.newInstance();
16DocumentBuilder documentBuilder = documentBuildFactory.newDocumentBuilder();
17documentBuilder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));

The example also parses the generated string with the Java XML API to confirm that it is valid XML. A result can follow this structure:

 1<validationResult>
 2<isValid>false</isValid>
 3<details>
 4  <techniqueResult>
 5    <technique>H35</technique>
 6    <criterion>1.1.1</criterion>
 7    <type>Error</type>
 8    <description>Check that the applet element contains an alt attribute with a text alternative for the applet. </description>
 9    <source><![CDATA[<applet code="tictactoe.class" width="250" height="250">tic-tac-toe game</applet>]]>
10    </source>
11  </techniqueResult>
12  <techniqueResult>
13    <technique>H37</technique>
14    <criterion>1.1.1</criterion>
15    <type>Error</type>
16    <description>Img element missing an alt attribute. The value of this attribute is referred to as "alt text".</description>
17    <source><![CDATA[<img src="image1.jpeg">]]>
18    </source>
19  </techniqueResult>
20  
21   ...
22
23 </details>
24</validationResult>

Common Issues When Reading or Saving Results

IssueExplanation and fix
Checking only getSuccess()The overall boolean does not explain individual findings. Inspect getDetails(), then the rule’s technique results, errors, or warnings.
Expecting JSON or XML from saveToString()saveToString() returns the text representation. Use saveTo(writer, ValidationResultSaveFormat.JSON) or .XML to select a structured format.
Using {0} placeholders with Java String.format()Java uses format specifiers such as %s. Curly-brace placeholders are printed literally.
Treating an automated pass as proof of conformanceAutomated checks cover machine-testable rules. Manual review and assistive-technology testing are still required.

FAQ

How do I find which accessibility rule failed?

If ValidationResult.getSuccess() is false, iterate through getDetails(). For each unsuccessful RuleValidationResult, use getRule() for the code and description, then inspect getErrors(), getWarnings(), or getResults().

Which formats can I use to save accessibility validation results?

ValidationResultSaveFormat supports text, JSON, and XML. Use saveToString() for a text string or saveTo(writer, format) when you need to choose the format.

Does a successful automated result guarantee WCAG 2.0 conformance?

No. A successful result means that the selected automated rules did not report a failure. Complete accessibility evaluation also requires manual checks, content review, keyboard testing, and testing with relevant assistive technologies.

Related Articles

Other Platforms

Try the Online Web Accessibility Checker

Use the free online Web Accessibility Checker for a quick page scan before implementing or extending Java accessibility checks.

Web Accessibility Checker