---
title: "Write a custom HTML accessibility rule in C#"
url: https://recursiveai.org/onehtml/cookbook/write-custom-accessibility-rule/
description: "Implement IAccessibilityRule and register a custom accessible-name policy with the onehtml checker. Run it against two local checkout buttons in C#."
version: "1.6.0"
---

# Write a custom HTML accessibility rule in C#

**onehtml** is a free, open-source HTML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneHtml.Accessibility.Validation) · [GitHub](https://github.com/recursive-ai-oss/onehtml-csharp) · [Docs](https://recursiveai.org/onehtml/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/cookbook/write-custom-accessibility-rule/write-custom-accessibility-rule.zip)

Implement `IAccessibilityRule` to flag checkout buttons whose name is just “Continue.”

```shell
dotnet add package RecursiveAI.OneHtml.Accessibility.Validation
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Accessibility
    .Validation;

// Add CheckoutNameRule.cs (below).
var rule = new CheckoutNameRule();
var checker = Checker.WithRules([rule]);
var doc = Document.Parse("""
    <button data-checkout>Continue</button>
    <button data-checkout>
      Review order
    </button>
    """);
foreach (var result in
    checker.Check(doc).Results)
    Console.WriteLine(result.Outcome);
```

Prints the two outcomes in document order:

```text
Failed
Passed
```

Unzip [the example](https://recursiveai.org/onehtml/cookbook/write-custom-accessibility-rule/write-custom-accessibility-rule.zip), then `dotnet run`.

## The full program

Use the snippet above as `Program.cs` and add this `CheckoutNameRule.cs` file to the same project. Both files are in the download. The rule reads the button’s computed accessible name, the label exposed to assistive technology.

```csharp
using RecursiveAI.OneHtml.Accessibility.Validation;
using RecursiveAI.OneHtml.Accessibility.Validation.Catalogue;

sealed class CheckoutNameRule : IAccessibilityRule
{
    private const string Id = "shop-checkout-name";

    public RuleDescriptor Descriptor { get; } = new(
        id: Id,
        sources: [RuleSource.Own(Id)],
        criteria: [],
        bestPractice: true,
        needs: RuleNeeds.Static,
        fix: null,
        noFixReason: "The author must choose a name that fits the action.");

    public string Description => "Checkout buttons need a specific name.";
    public string Help => "Name the action, such as Review order.";
    public Impact Impact => Impact.Moderate;

    public void Evaluate(CheckContext context, RuleReporter reporter)
    {
        foreach (var element in context.Elements())
        {
            reporter.CancellationToken.ThrowIfCancellationRequested();
            if (!element.Matches("button[data-checkout]") ||
                !context.IsExposed(element) ||
                context.Find(element) is not { } button)
                continue;

            string name = button.Name.Value;
            if (string.IsNullOrWhiteSpace(name) ||
                string.Equals(name, "Continue", StringComparison.OrdinalIgnoreCase))
                reporter.Failed(element, Help);
            else
                reporter.Passed(element);
        }
    }
}
```

The rule checks only exposed buttons marked `data-checkout`. If no button is eligible, the checker returns an `Inapplicable` result; a duplicate rule ID is rejected with `ArgumentException`.

## Variations

**Check the corrected label.** Append this to `Program.cs` after the snippet at the top:

```csharp
var fixedDoc = Document.Parse("""
    <button data-checkout>Review order</button>
    """);
foreach (var result in checker.Check(fixedDoc).Results)
    Console.WriteLine(result.Outcome);
```

```text
Passed
```

## Related recipes

[Resolve accessible names and descriptions](https://recursiveai.org/onehtml/cookbook/resolve-accessible-names-and-descriptions/) · [Run WCAG checks in CI with SARIF](https://recursiveai.org/onehtml/cookbook/wcag-checks-ci-sarif/)

---

## The short answer

Implement `IAccessibilityRule`, register an instance, and run `Check` on the parsed document. `Checker.WithRules` runs only the supplied rules, which makes it useful for testing one local policy in isolation. The interface separates a rule’s metadata (`Descriptor`, `Description`, `Help`, and `Impact`) from `Evaluate`, where the rule reports findings about specific elements.

## How do you make a button accessible?

Use a native `<button>` for an action and give it a name that tells the user what it does. Ordinary button text can supply the name; an icon-only button needs a name from another source, such as `aria-label`. The [W3C rule for button names](https://www.w3.org/WAI/standards-guidelines/act/rules/97a4e1/) checks that a button has a nonempty name. That does not mean the name tells someone enough about the action. A team might decide that “Continue” is too vague on its checkout controls, even though it is nonempty.

Use `context.Find(element)` to read the computed name rather than searching for an `aria-label` attribute. A button can get its name from visible text or `aria-labelledby`, and an explicit name can differ from the text inside the element. This recipe checks the name that onehtml calculated. It doesn’t try to rank every possible name: its policy rejects empty names and one particular vague label within a particular set of buttons.

## Should you run all accessibility rules or only selected rules?

Run the custom rule on its own while you’re testing the policy. The fixture has two eligible targets, so you can distinguish a working rule from one that reports nothing because the selector missed both buttons. To run the custom rule alongside the built-in rules, replace the `Checker.WithRules` line in `Program.cs` with:

```csharp
var checker = new Checker(privateRules: [rule]);
```

The report now includes built-in results as well as the custom rule’s `Failed` and `Passed` results. Give the policy an ID that doesn’t collide with another rule so you can identify its results independently.

A private policy isn’t a WCAG requirement just because it runs in the same checker. The descriptor above declares a best practice with no WCAG criterion IDs. Keep it stateless, report against the original element, and leave the name choice to the author. The right replacement for “Continue” depends on what the button actually does, so the rule gives advice rather than rewriting the HTML.
