SharpRuneOpen playground

Forms and validation

Build a form with EditForm, the Input components and DataAnnotations rules, and choose between OnValidSubmit and OnSubmit.

  • 25 min
  • Read, predict, then run
Blazor WebAssembly project

In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.

At a glance

Who decides that the form is valid

OnValidSubmit / OnInvalidSubmit
  • EditForm validates the whole model for you
  • Any message left: OnInvalidSubmit
  • No messages: OnValidSubmit
  • The empty sign-up gets 5 messages
OnSubmit
  • Runs on every submit; nothing is validated first
  • Your handler calls Validate() when it chooses
  • Fits saving a draft, or an async check first
  • Cannot be combined with the other two

Either way the EditContext tracks changed fields and messages, and a changed field is validated on its own. Client checks help the user; the server must validate again.

What EditForm builds for you

EditForm renders an ordinary HTML form element, but most of its work happens in C#. When you pass Model, it creates an EditContext for that object. The EditContext is the memory of the form. For each field it records whether you changed it, and through validation message stores it records which messages belong to which field. A field is identified by a FieldIdentifier: the model object plus the property name.

EditForm hands the EditContext to everything inside it as a cascading value. That is how InputText or ValidationMessage find the form without any parameter from you. When you write @bind-Value="signUp.Name", the Razor compiler produces three parameters: Value, ValueChanged and ValueExpression. The expression tells the input which property it edits, so it can build the FieldIdentifier. When you change the text and leave the field, the input converts the text to the property type, writes it through ValueChanged and calls NotifyFieldChanged on the EditContext. Each input also asks the EditContext for its CSS classes. That is where modified, valid and invalid come from, and the project's app.css colors the borders with them.

How DataAnnotationsValidator runs the rules

DataAnnotationsValidator renders nothing. It subscribes to two EditContext events. When one field changes, it validates only that property with Validator.TryValidateProperty and replaces that field's messages. When the whole form is validated, it runs Validator.TryValidateObject with validateAllProperties set to true and replaces all messages. After each pass it tells the EditContext that the validation state changed, and ValidationSummary and every ValidationMessage render again.

The rules are attributes on the model. [Required] fails for null and for empty or whitespace strings. [StringLength], [Range] and [EmailAddress] treat null as valid, which is why Name in the project has both [Required] and [StringLength]. [EmailAddress] is a light check: it wants one @ that is not at either end. A custom rule is a class that derives from ValidationAttribute and overrides IsValid, like MustBeTrue in the project. [Required] cannot do that job, because a bool always has a value.

Some messages come from the inputs themselves. If InputNumber or InputDate cannot parse the browser's text, it adds a parsing message to the EditContext before any attribute runs, so the form stays invalid until you fix the text. Also note that DataAnnotationsValidator validates only the top-level properties of the model. It does not walk into nested objects or collections.

OnValidSubmit, OnInvalidSubmit and OnSubmit

When the form is submitted and you did not set OnSubmit, EditForm calls EditContext.Validate(). Validate raises the event that DataAnnotationsValidator listens to, then returns true if no messages remain. EditForm calls OnValidSubmit for true and OnInvalidSubmit for false. Without a validator in the form, no rule adds messages, so OnValidSubmit runs for any input the fields can parse.

When you set OnSubmit, EditForm calls it on every submit and validates nothing. Your handler receives the EditContext and decides. That fits cases where you need control, for example saving a draft whether or not it is valid, or running an async check before you call Validate. Setting OnSubmit together with OnValidSubmit or OnInvalidSubmit is an error, and EditForm throws an exception.

You give EditForm either Model or EditContext, never both. Creating the EditContext yourself gives you its API: OnFieldChanged, IsModified, MarkAsUnmodified, GetValidationMessages and Validate. If you assign a new model or a new EditContext, EditForm builds a fresh form inside, with no modified flags and no messages. The project uses that to reset a form after a successful submit.

Trace the Forms Lab project

Open the Model page and tap Sign up with nothing filled in. EditForm validates the whole SignUp object. Name, Email, Track and StartDate fail [Required]. AcceptRules fails MustBeTrue. Seats starts at 1, so [Range(1, 5)] passes. The summary lists five messages, each field shows its own message, and OnInvalidSubmit adds one to the rejected count. Now type A in Name and leave the field. Only Name is validated again, and its message changes to the length rule. Fill everything correctly and submit. OnValidSubmit builds the Saved line, formats StartDate as yyyy-MM-dd and assigns a new SignUp, which clears the form.

On the EditContext page the model is a small Feedback class defined inside the component. Rating starts at 0, which fails [Range(1, 5)], and Comment may stay empty because [StringLength] accepts null. Each change raises OnFieldChanged, so Last changed field and Form modified update. Send calls Validate() itself and, when it passes, MarkAsUnmodified.

The companion runs the same attributes without a browser. The empty form gives five messages. The form with typos gives four with validateAllProperties: true and none with false, because only [Required] runs in that mode.

Common mistakes

Treating client validation as security is the biggest one. A WebAssembly app runs on the user's device, and anyone can change or skip its code. Validate again on the server that stores the data. The same attribute classes work there, which is one reason to keep rules on the model.

Other mistakes are smaller. Putting [Required] on int, bool or DateOnly does nothing, because those types always have a value; use a nullable type such as DateOnly?, a [Range], or a custom attribute. Calling TryValidateObject in your own code without validateAllProperties: true checks only [Required]. A ValidationMessage whose For points at a different property than @bind-Value never shows the message you expect. HTML attributes such as required, min or type="email" let the browser block the submit with its own popup before Blazor sees it; the project uses inputmode="email" to get the email keyboard without that. Finally, if code changes a model property directly, the field's message does not update until the next validation, because no input called NotifyFieldChanged.

Practice and review

Add a Phone property with [Phone] and a field for it. Before you run anything, copy the property into the companion and predict its output for an empty value and for the text abc. Then make Track a nullable enum, keep [Required], and build the options in InputSelect from Enum.GetValues. Next, implement IValidatableObject on SignUp with the rule that the Games track needs at least two seats, and return the result with the member name Seats. Notice that this rule runs only when the whole object is validated and only after the attributes pass, so it appears on submit, not while you type. Finally, on the EditContext page, add a second button that saves a draft without validation.

Key points
  • EditForm creates or receives an EditContext and cascades it to the inputs and validators inside it.
  • DataAnnotationsValidator validates one property after a field change and the whole object on submit.
  • OnValidSubmit and OnInvalidSubmit run after automatic validation; OnSubmit runs always and leaves validation to you.
  • Validator.TryValidateObject needs validateAllProperties: true to check more than [Required].
  • Client validation helps the user; the server must validate again.
Runs on this device: SharpRune compiles the Razor components and C# here and runs the app in Preview on .NET 9 WebAssembly. The same files run on a computer with the .NET 9 SDK and dotnet run.

Forms and validation — Blazor WebAssembly project

Run the project

  1. Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
  2. On the Model page, tap Sign up with the form empty. Then fill the fields one by one and watch each message go away when its field becomes valid.
  3. Open EditContext in the header. Type a name and watch Form modified and Last changed field, then tap Send with the rating still at 0.
  4. Change a .razor file and tap Run again to rebuild.
  5. On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.

Download the project ↗

Project files

FormsLab.csprojDownload file ↗
FormsLab.csproj
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>FormsLab</AssemblyName>
    <RootNamespace>FormsLab</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
  </ItemGroup>

</Project>
Program.csDownload file ↗
Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using FormsLab;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// Forms need no extra services. EditForm, the Input* components and
// DataAnnotationsValidator come with Microsoft.AspNetCore.Components.Forms.
await builder.Build().RunAsync();
App.razorDownload file ↗
App.razor
@* The root component. This small app has no layout file,
   so the shared header sits here, around the Router. *@
<header class="bar">
    <span class="brand">Forms Lab</span>
    <nav>
        <NavLink href="" Match="NavLinkMatch.All">Model</NavLink>
        <NavLink href="edit-context">EditContext</NavLink>
    </nav>
</header>

<main>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <h1>Not found</h1>
            <p>There is no page at this address.</p>
        </NotFound>
    </Router>
</main>
_Imports.razorDownload file ↗
_Imports.razor
@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using FormsLab
@using FormsLab.Models
Models/SignUp.csDownload file ↗
Models/SignUp.cs
using System.ComponentModel.DataAnnotations;

namespace FormsLab.Models;

// A plain C# class. The attributes are the validation rules;
// DataAnnotationsValidator reads them, and so does Validator in a console app.
public sealed class SignUp
{
    [Required(ErrorMessage = "Enter your name.")]
    [StringLength(40, MinimumLength = 2, ErrorMessage = "Name must be 2 to 40 characters.")]
    public string? Name { get; set; }

    [Required(ErrorMessage = "Enter an email address.")]
    [EmailAddress(ErrorMessage = "This is not a valid email address.")]
    public string? Email { get; set; }

    [Range(1, 5, ErrorMessage = "Choose 1 to 5 seats.")]
    public int Seats { get; set; } = 1;

    [Required(ErrorMessage = "Pick a track.")]
    public string? Track { get; set; }

    [Required(ErrorMessage = "Pick a start date.")]
    public DateOnly? StartDate { get; set; }

    [MustBeTrue(ErrorMessage = "Accept the workshop rules.")]
    public bool AcceptRules { get; set; }
}

// [Required] does not help with a bool: false is a value. A small custom attribute does.
public sealed class MustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object? value) => value is true;
}
Pages/ContextForm.razorDownload file ↗
Pages/ContextForm.razor
@page "/edit-context"
@implements IDisposable

<PageTitle>EditContext</PageTitle>

<h1>EditContext and OnSubmit</h1>

<p class="muted">This form creates its own EditContext and handles <code>OnSubmit</code>, so the page decides when to validate.</p>

<EditForm EditContext="editContext" OnSubmit="Submit">
    <DataAnnotationsValidator />

    <div class="field">
        <label for="name">Name</label>
        <InputText id="name" @bind-Value="feedback.Name" />
        <ValidationMessage For="() => feedback.Name" />
    </div>

    <div class="field">
        <label for="rating">Rating (1 to 5)</label>
        <InputNumber id="rating" @bind-Value="feedback.Rating" />
        <ValidationMessage For="() => feedback.Rating" />
    </div>

    <div class="field">
        <label for="comment">Comment</label>
        <InputTextArea id="comment" rows="3" @bind-Value="feedback.Comment" />
        <ValidationMessage For="() => feedback.Comment" />
    </div>

    <div class="row">
        <button type="submit" class="primary">Send</button>
        <button type="button" @onclick="Reset">Reset</button>
    </div>
</EditForm>

<dl class="facts">
    <dt>Form modified</dt>
    <dd>@(editContext.IsModified() ? "yes" : "no")</dd>
    <dt>Last changed field</dt>
    <dd>@(lastField ?? "none")</dd>
    <dt>Messages in the EditContext</dt>
    <dd>@editContext.GetValidationMessages().Count()</dd>
    <dt>Last submit</dt>
    <dd>@lastSubmit</dd>
</dl>

@code {
    private Feedback feedback = new();
    private EditContext editContext = default!;
    private string? lastField;
    private string lastSubmit = "none yet";

    protected override void OnInitialized() => Attach(new Feedback());

    private void Attach(Feedback model)
    {
        feedback = model;
        editContext = new EditContext(feedback);
        // Raised each time an Input component writes a new value into the model.
        editContext.OnFieldChanged += FieldChanged;
    }

    private void FieldChanged(object? sender, FieldChangedEventArgs e) =>
        lastField = e.FieldIdentifier.FieldName;

    // OnSubmit runs on every submit. Nothing is validated unless you ask.
    private void Submit(EditContext context)
    {
        if (context.Validate())
        {
            lastSubmit = $"sent: {feedback.Name} rated {feedback.Rating}";
            context.MarkAsUnmodified();
        }
        else
        {
            lastSubmit = "not sent, fix the messages above";
        }
    }

    private void Reset()
    {
        editContext.OnFieldChanged -= FieldChanged;
        Attach(new Feedback());
        lastField = null;
        lastSubmit = "form reset";
    }

    public void Dispose() => editContext.OnFieldChanged -= FieldChanged;

    public sealed class Feedback
    {
        [Required(ErrorMessage = "Enter your name.")]
        public string? Name { get; set; }

        [Range(1, 5, ErrorMessage = "Rate from 1 to 5.")]
        public int Rating { get; set; }

        [StringLength(120, ErrorMessage = "Keep the comment under 120 characters.")]
        public string? Comment { get; set; }
    }
}
Pages/SignUpForm.razorDownload file ↗
Pages/SignUpForm.razor
@page "/"

<PageTitle>Sign up</PageTitle>

<h1>Workshop sign-up</h1>

<p class="muted">An EditForm with <code>Model</code>. Tap Sign up with the form empty to see every rule fail.</p>

@* EditForm creates an EditContext for the model and renders a <form>. *@
<EditForm Model="signUp" OnValidSubmit="Save" OnInvalidSubmit="CountRejected">
    @* Reads the attributes on SignUp and puts messages into the EditContext. *@
    <DataAnnotationsValidator />
    @* Lists every message the EditContext holds. *@
    <ValidationSummary />

    <div class="field">
        <label for="name">Name</label>
        <InputText id="name" @bind-Value="signUp.Name" autocomplete="name" />
        <ValidationMessage For="() => signUp.Name" />
    </div>

    <div class="field">
        <label for="email">Email</label>
        @* inputmode asks for the email keyboard without the browser's own validation. *@
        <InputText id="email" inputmode="email" autocapitalize="off" @bind-Value="signUp.Email" />
        <ValidationMessage For="() => signUp.Email" />
    </div>

    <div class="field">
        <label for="seats">Seats</label>
        <InputNumber id="seats" @bind-Value="signUp.Seats" />
        <ValidationMessage For="() => signUp.Seats" />
    </div>

    <div class="field">
        <label for="track">Track</label>
        <InputSelect id="track" @bind-Value="signUp.Track">
            <option value="">Choose a track…</option>
            <option value="Web">Web</option>
            <option value="Mobile">Mobile</option>
            <option value="Games">Games</option>
        </InputSelect>
        <ValidationMessage For="() => signUp.Track" />
    </div>

    <div class="field">
        <label for="start">Start date</label>
        <InputDate id="start" @bind-Value="signUp.StartDate" />
        <ValidationMessage For="() => signUp.StartDate" />
    </div>

    <label class="check">
        <InputCheckbox @bind-Value="signUp.AcceptRules" />
        I accept the workshop rules
    </label>
    <ValidationMessage For="() => signUp.AcceptRules" />

    <div class="row">
        <button type="submit" class="primary">Sign up</button>
    </div>
</EditForm>

@if (saved is not null)
{
    <p class="result" role="status">Saved: @saved</p>
}

<p class="muted">Valid submits: @validCount · Rejected submits: @rejectedCount</p>

@code {
    private SignUp signUp = new();
    private string? saved;
    private int validCount;
    private int rejectedCount;

    // OnValidSubmit runs only when every rule passes.
    private void Save()
    {
        validCount++;
        saved = $"{signUp.Name} ({signUp.Email}), {signUp.Seats} seat(s), {signUp.Track} track, starts {signUp.StartDate:yyyy-MM-dd}";

        // A new model gives EditForm a new EditContext, so the form starts clean.
        signUp = new SignUp();
    }

    // OnInvalidSubmit runs when at least one rule fails. The messages are already on screen.
    private void CountRejected() => rejectedCount++;
}
wwwroot/index.htmlDownload file ↗
wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Forms Lab</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="FormsLab.styles.css" />
</head>
<body>
    <div id="app">
        <p class="loading">Starting .NET…</p>
    </div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">✕</span>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.cssDownload file ↗
wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #6b4eff;
    --line: #d8d6e4;
    --danger: #d32f2f;
    --ok: #2e7d32;
}

body {
    margin: 0;
    font-family: -apple-system, system-ui, sans-serif;
    line-height: 1.5;
}

a, button, input, label { touch-action: manipulation; }

select { touch-action: manipulation; }

.bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px 16px;
    padding: 12px 16px;
    background: #1f1b3a;
    color: #fff;
}

.brand {
    font-weight: 700;
    margin-right: auto;
}

.bar nav {
    display: flex;
    gap: 4px;
}

.bar nav a {
    color: #d9d4ff;
    text-decoration: none;
    padding: 6px 10px;
    border-radius: 8px;
}

.bar nav a.active {
    background: var(--accent);
    color: #fff;
}

main {
    padding: 20px 16px 40px;
    max-width: 720px;
    margin: 0 auto;
    box-sizing: border-box;
}

h1 {
    font-size: 1.8rem;
    margin: 0 0 12px;
}

h1:focus {
    outline: none;
}

h2 {
    font-size: 1.15rem;
    margin: 24px 0 8px;
}

.loading {
    padding: 32px 16px;
    color: #777;
}

.muted {
    color: #777;
}

.row {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 12px 0;
}

input:not([type=checkbox]), select, textarea {
    font: inherit;
    color: inherit;
    background: transparent;
    padding: 8px 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-width: 0;
    box-sizing: border-box;
}

button {
    font: inherit;
    padding: 8px 14px;
    border-radius: 8px;
    border: 1px solid var(--line);
    background: transparent;
    color: inherit;
}

button.primary {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
}

button:disabled {
    opacity: 0.45;
}

button.link {
    border: none;
    color: var(--accent);
    padding: 4px 6px;
}

code {
    font-size: 0.9em;
    overflow-wrap: anywhere;
}

#blazor-error-ui {
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #ffe8a3;
    color: #222;
}

.field {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-bottom: 14px;
}

.field input, .field select, .field textarea {
    width: 100%;
    min-height: 42px;
}

.check {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 8px 0 4px;
}

.check input {
    width: 20px;
    height: 20px;
    margin: 0;
}

/* Blazor adds these classes to Input components: modified, valid, invalid. */
.modified.valid:not([type=checkbox]) {
    border-color: var(--ok);
}

.invalid:not([type=checkbox]) {
    border-color: var(--danger);
}

input[type=checkbox].invalid {
    outline: 2px solid var(--danger);
}

.validation-message {
    color: var(--danger);
    font-size: 0.9rem;
}

/* ValidationSummary renders <ul class="validation-errors">. */
.validation-errors {
    margin: 0 0 16px;
    padding: 10px 12px 10px 30px;
    border: 1px solid var(--danger);
    border-radius: 10px;
}

.result {
    padding: 10px 12px;
    border-radius: 10px;
    background: rgba(46, 125, 50, 0.12);
}

.facts {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 6px 12px;
    margin: 20px 0 0;
    padding: 12px;
    border: 1px solid var(--line);
    border-radius: 10px;
}

.facts dt {
    color: #777;
}

.facts dd {
    margin: 0;
    font-weight: 600;
}

Expected result

On the Model page, submitting the empty form shows five messages in the red summary box and under the fields, red borders on the invalid inputs, and 'Rejected submits: 1'. When every field is valid and the rules box is checked, Sign up shows a line such as 'Saved: Ada (ada@example.com), 2 seat(s), Mobile track, starts 2026-12-01', increases 'Valid submits' and clears the form. On the EditContext page, typing in a field sets Form modified to yes and names the field. Send with an empty name and rating 0 shows two messages and 'not sent, fix the messages above'. A name with a rating from 1 to 5 shows 'sent: <name> rated <n>' and Form modified goes back to no. Reset clears the fields and the messages.

The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.

C# companion practice

Program.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

// The same SignUp class as Models/SignUp.cs in the Blazor project, checked without a browser.
Report("Empty form", new SignUp(), validateAll: true);

var typo = new SignUp
{
    Name = "A",
    Email = "ada-at-example",
    Seats = 9,
    Track = "Web",
    StartDate = new DateOnly(2026, 12, 1),
    AcceptRules = false
};
Report("Typos, all rules", typo, validateAll: true);
Report("Typos, [Required] only", typo, validateAll: false);

typo.Name = "Ada";
typo.Email = "ada@example.com";
typo.Seats = 2;
typo.AcceptRules = true;
Report("Fixed form", typo, validateAll: true);

// One property at a time, the way DataAnnotationsValidator checks a field after you edit it.
typo.Email = "ada.example.com";
var results = new List<ValidationResult>();
var context = new ValidationContext(typo) { MemberName = nameof(SignUp.Email) };
bool emailOk = Validator.TryValidateProperty(typo.Email, context, results);
Console.WriteLine($"Email field alone: {(emailOk ? "valid" : results[0].ErrorMessage)}");

static void Report(string title, object model, bool validateAll)
{
    var results = new List<ValidationResult>();
    bool valid = Validator.TryValidateObject(model, new ValidationContext(model), results, validateAll);
    Console.WriteLine($"{title}: {(valid ? "valid" : results.Count + " problem(s)")}");
    foreach (var result in results)
    {
        Console.WriteLine($"  {string.Join(",", result.MemberNames)}: {result.ErrorMessage}");
    }
}

public sealed class SignUp
{
    [Required(ErrorMessage = "Enter your name.")]
    [StringLength(40, MinimumLength = 2, ErrorMessage = "Name must be 2 to 40 characters.")]
    public string? Name { get; set; }

    [Required(ErrorMessage = "Enter an email address.")]
    [EmailAddress(ErrorMessage = "This is not a valid email address.")]
    public string? Email { get; set; }

    [Range(1, 5, ErrorMessage = "Choose 1 to 5 seats.")]
    public int Seats { get; set; } = 1;

    [Required(ErrorMessage = "Pick a track.")]
    public string? Track { get; set; }

    [Required(ErrorMessage = "Pick a start date.")]
    public DateOnly? StartDate { get; set; }

    [MustBeTrue(ErrorMessage = "Accept the workshop rules.")]
    public bool AcceptRules { get; set; }
}

public sealed class MustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object? value) => value is true;
}
Open C# practice

C# practice output

Empty form: 5 problem(s)
  Name: Enter your name.
  Email: Enter an email address.
  Track: Pick a track.
  StartDate: Pick a start date.
  AcceptRules: Accept the workshop rules.
Typos, all rules: 4 problem(s)
  Name: Name must be 2 to 40 characters.
  Email: This is not a valid email address.
  Seats: Choose 1 to 5 seats.
  AcceptRules: Accept the workshop rules.
Typos, [Required] only: valid
Fixed form: valid
Email field alone: This is not a valid email address.
Try this
If a message never appears, check that DataAnnotationsValidator is inside the EditForm and that ValidationMessage For points at the same property as @bind-Value. In your own code, pass validateAllProperties: true to TryValidateObject.

Further reading