Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aspose-com-gists/18bbe9938170231f557336d7305fe57c to your computer and use it in GitHub Desktop.
Save aspose-com-gists/18bbe9938170231f557336d7305fe57c to your computer and use it in GitHub Desktop.
Check website accessibility using .NET API and find out if your website is WCAG compliant

Code Examples for Checking Web Accessibility

This gist repository contains C# examples that accompany the Web Accessibility chapter in the Aspose.HTML for .NET documentation. These examples demonstrate how to validate HTML content for accessibility according to the WCAG standard and identify errors and warnings to improve them.

What's Included?

The repository contains examples illustrating how to:

  • Check web documents against WCAG standards using built-in validators and accessibility rule sets.
  • Check for missing alternative text in image elements.
  • Evaluate color contrast and compare it to accessibility standards.
  • Evaluate multimedia elements to ensure compliance with accessibility guidelines.
  • Create reports describing accessibility violations found in an HTML document.
  • Configure accessibility checking and use rule sets to control the level and focus of analysis.
  • Query accessibility principles, guidelines, and criteria using the Aspose.HTML API.

How to Use These Examples

  1. Install the latest Aspose.HTML for .NET via NuGet.
  2. Explore the gists in this repository and copy the relevant code to your project.
  3. Configure paths, settings, and inputs to suit your environment.
  4. Run your project to see the example in action.

You can download a free trial of Aspose.HTML for .NET and use a temporary license for unrestricted access.

Documentation

Detailed explanations and full context for each example can be found in the Web Accessibility sections of the official documentation.

Other Related Resources

Prerequisites

To run the examples, you need:

  • .NET Platforms: .NET Platforms: .NET 5.0, .NET Framework 4.6.1+, or .NET Core 2.0+
  • Supported OS: Windows, Linux, macOS
  • The Aspose.HTML for .NET library (you can install it via NuGet: Install-Package Aspose.Html).
Aspose.HTML for .NET – Check Web Accessibility
// Perform web accessibility validation on HTML document, focusing on the use of colors and color contrast
// Learn more: https://docs.aspose.com/html/net/color-contract-accessibility/
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "check-color.html");
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
// Get criterion by code, for example 1.4.3
Criterion criterion143 = guideline.GetCriterion("1.4.3");
// Get criterion by code, for example 1.4.6
Criterion criterion146 = guideline.GetCriterion("1.4.6");
// Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(new IRule[] { criterion143, criterion146 }, ValidationBuilder.All);
using (HTMLDocument document = new HTMLDocument(documentPath))
{
ValidationResult validationResult = validator.Validate(document);
if (!validationResult.Success)
{
Console.WriteLine(validationResult.SaveToString());
}
}
// Check color contrast on an HTML document using C#
// Learn more: https://docs.aspose.com/html/net/color-contract-accessibility/
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "check-color.html");
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
// Get criterion by code, for example 1.4.3
Criterion criterion = guideline.GetCriterion("1.4.3");
// Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(criterion, ValidationBuilder.All);
using (HTMLDocument document = new HTMLDocument(documentPath))
{
ValidationResult validationResult = validator.Validate(document);
if (!validationResult.Success)
{
// Get all result details
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// If the result of the rule is unsuccessful
if (!ruleResult.Success)
{
// Get errors list
foreach (ITechniqueResult result in ruleResult.Errors)
{
// Check the type of the erroneous element, in this case we have an error in the html element rule
if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
{
// Element of file with error
HTMLElement rule = (HTMLElement)result.Error.Target.Item;
Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
Console.WriteLine("CSS Rule: {0}", rule.OuterHTML);
}
}
}
}
}
}
// Validate an HTML document using specific rule codes with C#
// Learn more: https://docs.aspose.com/html/net/web-accessibility-rules/
string htmlPath = Path.Combine(DataDir, "input.html");
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// List of necessary rules for checking (rule code according to the specification)
string[] rulesCode = new string[] { "H2", "H37", "H67", "H86" };
// Get the required IList<Rule> rules from the rules reference
IList<IRule> rules = webAccessibility.Rules.GetRules(rulesCode);
// Create an accessibility validator, pass the found rules as parameters, and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(rules, ValidationBuilder.All);
// Initialize an object of the HTMLDocument
using (HTMLDocument document = new HTMLDocument(htmlPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Return the result in string format
// SaveToString - return only errors and warnings
Console.WriteLine(validationResult.SaveToString());
}
// Validate HTML image alt text accessibility with detailed error reporting using C#
// Learn more: https://docs.aspose.com/html/net/screen-reader-accessibility/
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "alt-tag.html");
// Initialize webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get from the rules list Principle "1. Perceivable" by code "1" and get guideline "1.1 Text Alternatives"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.1");
// Create an accessibility validator - pass the found guideline as parameters and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(guideline, ValidationBuilder.All);
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument(documentPath))
{
ValidationResult validationResult = validator.Validate(document);
if (!validationResult.Success)
{
// Get all the result details
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// If the result of the rule is unsuccessful
if (!ruleResult.Success)
{
// Get an errors list
foreach (ITechniqueResult result in ruleResult.Errors)
{
// Check the type of the erroneous element, in this case, we have an error in the HTML Element
if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
{
HTMLElement rule = (HTMLElement)result.Error.Target.Item;
Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
Console.WriteLine("HTML Element: {0}", rule.OuterHTML);
}
}
}
}
}
}
// Validate HTML for accessibility and export all errors and warnings as a string
// Learn more: https://docs.aspose.com/html/net/web-accessibility-validation-results-save/
string htmlPath = Path.Combine(DataDir, "input.html");
using (HTMLDocument document = new HTMLDocument(htmlPath))
{
AccessibilityValidator validator = new WebAccessibility().CreateValidator();
ValidationResult validationresult = validator.Validate(document);
// get rules errors in string format
string content = validationresult.SaveToString();
// SaveToString - return only errors and warnings
// if everything is ok, it will return "validationResult:true"
Console.WriteLine(content);
}
// Validate HTML for accessibility and export all errors and warnings as an XML
// Learn more: https://docs.aspose.com/html/net/web-accessibility-validation-results-save/
string htmlPath = Path.Combine(DataDir, "input.html");
using (HTMLDocument document = new HTMLDocument(htmlPath))
{
AccessibilityValidator validator = new WebAccessibility().CreateValidator();
ValidationResult validationresult = validator.Validate(document);
using (StringWriter sw = new StringWriter())
{
validationresult.SaveTo(sw, ValidationResultSaveFormat.XML);
string xml = sw.ToString();
Console.WriteLine(xml);
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
}
catch (Exception)
{
Console.WriteLine("Wrong xml format");
}
}
}
// Check HTML for WCAG compliance and output failed rule codes and error messages
// Learn more: https://docs.aspose.com/html/net/web-accessibility-errors-and-warnings/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
string documentPath = Path.Combine(DataDir, "input.html");
// Initialize an object of the HTMLDocument class
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// list only unsuccessful rule
if (!ruleResult.Success)
{
// print the code and description of the rule
Console.WriteLine("{0}:{1} = {2}", ruleResult.Rule.Code, ruleResult.Rule.Description, ruleResult.Success);
// print the results of methods with errors
foreach (ITechniqueResult ruleDetail in ruleResult.Errors)
{
// print the code and description of the method
StringBuilder str = new StringBuilder(string.Format("\n{0}: {1} - {2}",
ruleDetail.Rule.Code, ruleDetail.Success,
ruleDetail.Rule.Description));
// get an error object
IError error = ruleDetail.Error;
// get a target object
Target target = error.Target;
// get error type and message
str.AppendFormat("\n\n\t{0} : {1}", error.ErrorTypeName, error.ErrorMessage);
if (target != null)
{
// Checking the type of the contained object for casting and working with it
if (target.TargetType == TargetTypes.CSSStyleRule)
{
ICSSStyleRule cssRule = (ICSSStyleRule)target.Item;
str.AppendFormat("\n\n\t{0}", cssRule.CSSText);
}
if (ruleDetail.Error.Target.TargetType == TargetTypes.CSSStyleSheet)
str.AppendFormat("\n\n\t{0}", ((ICSSStyleSheet)target.Item).Title);
if (ruleDetail.Error.Target.TargetType == TargetTypes.HTMLElement)
str.AppendFormat("\n\n\t{0}", ((HTMLElement)target.Item).OuterHTML);
}
Console.WriteLine(str.ToString());
}
}
}
}
// Validate HTML accessibility using C# and print all failed WCAG rule with their descriptions
// Learn more: https://docs.aspose.com/html/net/web-accessibility-validation-results/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
string documentPath = Path.Combine(DataDir, "input.html");
// Initialize an object of the HTMLDocument class
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Take a list of rules results
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// List only unsuccessful rule
if (!ruleResult.Success)
{
// Print the code and description of the rule
Console.WriteLine("{0}:{1}", ruleResult.Rule.Code, ruleResult.Rule.Description);
// Print the results of all methods
foreach (ITechniqueResult ruleDetail in ruleResult.Results)
{
// Print the code and description of the criterions
StringBuilder str = new StringBuilder(string.Format("\n{0}: {1} - {2}",
ruleDetail.Rule.Code, ruleDetail.Success,
ruleDetail.Rule.Description));
Console.WriteLine(str.ToString());
}
}
}
}
// Retrieve and display the code and description of an accessibility criterion
// Learn more: https://docs.aspose.com/html/net/web-accessibility-rules/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle principle = webAccessibility.Rules.GetPrinciple("1");
// Get guideline
Guideline guideline = principle.GetGuideline("1.1");
// Get criterion by code
Criterion criterion = guideline.GetCriterion("1.1.1");
if (criterion != null)
{
Console.WriteLine("{0}:{1} - {2}", criterion.Code, criterion.Description, criterion.Level); // output: 1.1.1:Non-text Content - A
// Get all Sufficient Techniques and write to console
foreach (IRule technique in criterion.SufficientTechniques)
Console.WriteLine("{0}:{1}", technique.Code, technique.Description);
}
// Retrieve and display the code and description of an accessibility guideline
// Learn more: https://docs.aspose.com/html/net/web-accessibility-rules/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle principle = webAccessibility.Rules.GetPrinciple("1");
// Get guideline 1.1
Guideline guideline = principle.GetGuideline("1.1");
if (guideline != null)
{
Console.WriteLine("{0}:{1}", guideline.Code, guideline.Description, guideline); // output: 1.1:Text Alternatives
}
// Retrieve and display the code and description of an accessibility principle by its code
// Learn more: https://docs.aspose.com/html/net/web-accessibility-rules/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle rule = webAccessibility.Rules.GetPrinciple("1");
// Get code and description of principle
Console.WriteLine("{0}:{1}", rule.Code, rule.Description); // output: 1:Perceivable
// Retrieve and list accessibility rules by code with their descriptions from the rules repository
// Learn more: https://docs.aspose.com/html/net/web-accessibility-rules/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// List of rule codes can contain both technique codes and principles, guidelines and criteria - all rules that implement the interface IRule
string[] rulesCodes = new string[] { "H2", "H37", "H30", "1.1", "1.2.1" };
// Get a list of IRule objects; if a rule with the specified code is not found, it will not be in the list
IList<IRule> rules = webAccessibility.Rules.GetRules(rulesCodes);
// Get code and description of rule
foreach (IRule rule in rules)
Console.WriteLine("{0}:{1}", rule.Code, rule.Description);
// Validate HTML against WCAG rules using C#
// Learn more: https://docs.aspose.com/html/net/web-accessibility-validation-results/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "input.html");
// Initialize an object of the HTMLDocument class
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Checking for success
if (!validationResult.Success)
{
// Get a list of RuleValidationResult Details
foreach (RuleValidationResult detail in validationResult.Details)
{
Console.WriteLine("{0}:{1} = {2}", detail.Rule.Code, detail.Rule.Description, detail.Success);
}
}
}
// Validate HTML for multimedia accessibility using C#
// Learn more: https://docs.aspose.com/html/net/multimedia-accessibility/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get from the rules list Principle "1.Perceivable" by code "1" and get guideline "1.2 Time-based Media"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.2");
//Create an accessibility validator, pass the found guideline as parameters, and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(guideline, ValidationBuilder.All);
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument("https://www.youtube.com/watch?v=Yugq1KyZCI0&t=4s"))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Checking for success
if (!validationResult.Success)
{
// Get all result details
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// If the result of the rule is unsuccessful
if (!ruleResult.Success)
{
// Get an errors list
foreach (ITechniqueResult result in ruleResult.Errors)
{
// Check the type of the erroneous element
if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
{
HTMLElement rule = (HTMLElement)result.Error.Target.Item;
Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
Console.WriteLine("HTML Element: {0}", rule.OuterHTML);
}
}
}
}
}
}
// Check website for WCAG compliance in C#
// Learn more: https://docs.aspose.com/html/net/web-accessibility/
// Initialize webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/generators/video/"))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Checking for success
if (!validationResult.Success)
{
// Get a list of Details
foreach (RuleValidationResult detail in validationResult.Details)
{
Console.WriteLine("{0}:{1} = {2}", detail.Rule.Code, detail.Rule.Description, detail.Success);
}
}
}
// Check HTML document for WCAG compliance in C# and log each rule code, description, and pass status
// Learn more: https://docs.aspose.com/html/net/web-accessibility/
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator
AccessibilityValidator validator = webAccessibility.CreateValidator();
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "test-checker.html");
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult result = validator.Validate(document);
// Checking for success
if (!result.Success)
{
foreach (RuleValidationResult detail in result.Details)
{
// ... do the analysis here...
Console.WriteLine("{0}:{1} = {2}", detail.Rule.Code, detail.Rule.Description, detail.Success);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment