Skip to content

Add .NET support for client-side validation in Blazor SSR - #66441

Merged
oroztocil merged 9 commits into
mainfrom
oroztocil/validation-client-side-dotnet
May 14, 2026
Merged

oroztocil merged 9 commits into
mainfrom
oroztocil/validation-client-side-dotnet

Conversation

@oroztocil

@oroztocil oroztocil commented Apr 23, 2026 •

Copy link
Copy Markdown
Member

Description

This PR adds support for rendering client-side validation metadata from .NET validation attributes on Blazor SSR forms. This is the .NET-side part of the overall client-side form validation feature for Blazor SSR. It generates data-val-* HTML attributes from System.ComponentModel.DataAnnotations validation attributes so the companion JS library (in a separate PR) can enforce them client-side.

Contributes to #51040
Companion PR to #66420

What this enables

When a Blazor SSR form uses <DataAnnotationsValidator />, input components are automatically rendered with data-val-* attributes derived from model validation attributes ([Required], [Range], [EmailAddress], etc.). The companion JS library reads these attributes and provides instant, in-browser validation feedback without a server round-trip.

Client validation is activated automatically for SSR forms - no additional configuration is needed beyond the standard <DataAnnotationsValidator /> component that developers already use.

How it works

flowchart LR
    subgraph Server["Server (.NET)"]
        Model["<b>Model</b><br/>[Required]<br/>[Range] etc."]
        Service["<b>DefaultClient<br/>ValidationService</b><br/>reflection + caching"]
        Components["<b>InputBase</b> / <b>InputText</b><br/><b>InputRadioGroup</b><br/><b>ValidationMessage</b><br/><b>ValidationSummary</b>"]
        Model --> Service
        Service -->|"generates<br/>data-val-* dict"| Components
    end

    subgraph HTML["Rendered HTML"]
        Input["input data-val='true'<br/>data-val-required='...'"]
        Msg["div data-valmsg-for='...'"]
        Summary["div data-valmsg-summary='true'"]
    end

    Components --> Input
    Components --> Msg
    Components --> Summary
Loading
  1. DataAnnotationsValidator detects SSR mode (AssignedRenderMode is null) and stores the IClientValidationService into EditContext.Properties. This acts as a signal for child components to render client validation attributes.
  2. InputBase (and all derived components like InputText, InputNumber, etc.) reads the service from EditContext.Properties on each render, calls GetClientValidationAttributes(fieldIdentifier), and merges the resulting data-val-* attributes into AdditionalAttributes.
  3. InputRadioGroup / InputRadio - the group component extracts data-val-* attributes and passes them to child radio buttons via InputRadioContext. All radio buttons in the group receive the attributes; the JS library deduplicates by tracking one radio per name group.
  4. ValidationMessage renders data-valmsg-for="{fieldName}" and data-valmsg-replace="true" so the JS library can find and update the error message element.
  5. ValidationSummary renders data-valmsg-summary="true" so the JS library can find and populate the summary container.
sequenceDiagram
    participant DAV as DataAnnotationsValidator
    participant EC as EditContext.Properties
    participant IB as InputBase / InputText
    participant DCVS as DefaultClientValidationService

    Note over DAV: SSR render mode only
    DAV->>EC: Store IClientValidationService

    IB->>EC: Read IClientValidationService
    IB->>DCVS: GetClientValidationAttributes(fieldIdentifier)
    DCVS-->>IB: { "data-val": "true", "data-val-required": "..." }
    IB->>IB: Merge into AdditionalAttributes (first-wins)
Loading

Key design decisions

SSR-only activation. Client validation attributes are only rendered when AssignedRenderMode is null (static SSR). Interactive Blazor components use EditContext for server-side validation - adding data-val-* attributes would be redundant and could conflict with interactive validation state.

EditContext.Properties as communication channel. Rather than adding a new cascading parameter or modifying InputBase's parameter signature (which would be a breaking change), the IClientValidationService is stored in EditContext.Properties. This is an existing extensibility mechanism that doesn't require changes to component contracts.

First-wins attribute merging. When InputBase merges data-val-* attributes into AdditionalAttributes, it uses TryAdd (first-wins). This means developer-specified attributes take precedence - if a developer manually sets data-val-required in AdditionalAttributes, the generated value is not overwritten.

Singleton with caching. DefaultClientValidationService is registered as a singleton and caches attribute dictionaries per (Type, FieldName). Validation attributes are read from reflection once and reused across all requests.

Supported validation attributes

DefaultClientValidationService generates data-val-* attributes for these standard System.ComponentModel.DataAnnotations attributes:

.NET Attribute Generated data-val-* attributes
[Required] data-val-required
[StringLength] data-val-length, -min, -max
[MaxLength] data-val-maxlength, -max
[MinLength] data-val-minlength, -min
[Range] data-val-range, -min, -max
[RegularExpression] data-val-regex, -pattern
[Compare] data-val-equalto, -other
[EmailAddress] data-val-email
[Url] data-val-url
[Phone] data-val-phone
[CreditCard] data-val-creditcard
[FileExtensions] data-val-fileextensions, -extensions
Custom IClientValidationAdapter Developer-defined attributes

New public API surface

New namespace: Microsoft.AspNetCore.Components.Forms.ClientValidation

// Service that generates HTML attributes that describe rules for client-side validation
public interface IClientValidationService
{
    IReadOnlyDictionary<string, object>? GetClientValidationAttributes(FieldIdentifier fieldIdentifier);
}

// Extensibility interface for custom ValidationAttribute subclasses.
// Returns a sequence so a single attribute can emit multiple client-side rules.
public interface IClientValidationAdapter
{
    IEnumerable<ClientValidationRule> GetClientValidationRules(string errorMessage);
}

// Typed description of a single client-side validation rule.
public sealed class ClientValidationRule
{
    public ClientValidationRule(string name, string errorMessage);

    public string Name { get; }
    public string ErrorMessage { get; }
    public IReadOnlyDictionary<string, object?> Parameters { get; }

    // Parameter values are object? to allow non-string primitives (bools, numbers).
    // They are serialized to strings when the attribute is rendered as HTML.
    public ClientValidationRule WithParameter(string name, object? value);
}

Existing namespace: Microsoft.AspNetCore.Components.Forms

// New parameter on DataAnnotationsValidator
public class DataAnnotationsValidator
{
    [Parameter] public bool EnableClientValidation { get; set; } = true;
}

Existing namespace: Microsoft.Extensions.DependencyInjection

// Called by AddRazorComponents automatically.
// Needs to be public for dependency reasons (to avoid making new internal types public).
public static class ClientValidationServiceCollectionExtensions
{
    public static IServiceCollection AddClientValidation(this IServiceCollection services);
}

Custom validation attribute example

A ValidationAttribute that you own can opt into client-side rule emission by implementing IClientValidationAdapter and returning a typed ClientValidationRule (or several). The framework serializes each rule's Name, ErrorMessage, and Parameters into the corresponding data-val-<name> and data-val-<name>-<param> HTML attributes.

public class NotEqualToAttribute : ValidationAttribute, IClientValidationAdapter
{
    public string OtherProperty { get; }
    public NotEqualToAttribute(string otherProperty) => OtherProperty = otherProperty;

    protected override ValidationResult? IsValid(object? value, ValidationContext context) { /* server logic */ }

    public IEnumerable<ClientValidationRule> GetClientValidationRules(string errorMessage)
    {
        yield return new ClientValidationRule("notequalto", errorMessage)
            .WithParameter("other", "*." + OtherProperty);
    }
}

Renders as:

<input data-val="true"
       data-val-notequalto="Value must not equal OtherProperty."
       data-val-notequalto-other="*.OtherProperty" />

Note: Implementing IClientValidationAdapter requires owning the attribute source code. Registering external adapters is planned for a follow-up. It is intentionally out of scope for this PR.

Usage

No special setup is needed for standard Blazor SSR apps. Client validation activates automatically when <DataAnnotationsValidator /> is present in an SSR form:

<EditForm Model="model" FormName="register" Enhance>
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div>
        <label>Email</label>
        <InputText @bind-Value="model.Email" />
        <ValidationMessage For="@(() => model.Email)" />
    </div>

    <div>
        <label>Password</label>
        <InputText @bind-Value="model.Password" type="password" />
        <ValidationMessage For="@(() => model.Password)" />
    </div>

    <button type="submit">Submit</button>
</EditForm>

Rendered HTML (SSR):

<form method="post" data-enhance>
    <div data-valmsg-summary="true" class="validation-summary-valid">
        <ul></ul>
    </div>

    <label>Email</label>
    <input name="model.Email" data-val="true"
           data-val-required="The Email field is required."
           data-val-email="The Email field is not a valid e-mail address." />
    <span data-valmsg-for="model.Email" data-valmsg-replace="true" class="validation-message"></span>

    <label>Password</label>
    <input name="model.Password" type="password" data-val="true"
           data-val-required="The Password field is required."
           data-val-length="The field Password must be a string with a minimum length of 8 and a maximum length of 100."
           data-val-length-min="8" data-val-length-max="100" />
    <span data-valmsg-for="model.Password" data-valmsg-replace="true" class="validation-message"></span>

    <button type="submit">Submit</button>
</form>

To disable client validation for a specific form:

<DataAnnotationsValidator EnableClientValidation="false" />

Testing

25 unit tests covering:

  • All 12 supported validation attributes with correct data-val-* generation
  • StringLength with max-only (verifies min attribute is omitted when MinimumLength is 0)
  • Range with double values (verifies invariant culture formatting)
  • Multiple attributes on a single property
  • Properties with no validation attributes (returns null)
  • Non-existent properties (returns null)
  • [Display] and [DisplayName] integration in error messages
  • Fallback to property name when no display attribute is present
  • Result caching (same dictionary instance returned for same type+field)
  • Custom IClientValidationAdapter implementation
  • Nested model support (validation attributes on nested type properties)
  • Inherited validation attributes from base classes

Blazor SSR E2E tests will be provided either in a follow up PR, or added to this PR once the JS library PR is merged.

@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label Apr 23, 2026
@oroztocil
oroztocil force-pushed the oroztocil/validation-client-side-dotnet branch from bf49a46 to 3141a7b Compare April 23, 2026 17:26
@oroztocil
oroztocil requested a review from Copilot April 23, 2026 17:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds .NET-side support for Blazor SSR client-side validation by emitting unobtrusive data-val-* attributes from System.ComponentModel.DataAnnotations, plus message/summary hooks for a companion JS library.

Changes:

  • Introduces Microsoft.AspNetCore.Components.Forms.ClientValidation APIs and a default implementation that reflects over validation attributes and caches generated data-val-* dictionaries.
  • Activates SSR-only client validation via DataAnnotationsValidator and EditContext.Properties, and merges generated attributes into InputBase (including radio groups).
  • Updates ValidationMessage/ValidationSummary rendering to output data-valmsg-* markers, and adds unit tests for the default attribute generator.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 11 comments.

Show a summary per file
File Description
src/Components/Web/src/Forms/ValidationSummary.cs Adds SSR client-validation summary container (data-valmsg-summary) rendering.
src/Components/Web/src/Forms/ValidationMessage.cs Adds SSR client-validation message placeholder (data-valmsg-for, data-valmsg-replace) rendering.
src/Components/Web/src/Forms/InputRadioGroup.cs Extracts data-val-* attributes from group and passes them to child radios.
src/Components/Web/src/Forms/InputRadioContext.cs Adds cascading storage for client validation attributes for radio children.
src/Components/Web/src/Forms/InputRadio.cs Applies group-provided data-val-* attributes to each rendered radio input.
src/Components/Web/src/Forms/InputBase.cs Merges generated data-val-* attributes into AdditionalAttributes when client validation is enabled.
src/Components/Forms/test/DefaultClientValidationServiceTest.cs Adds unit tests for attribute generation/caching/custom adapters.
src/Components/Forms/src/PublicAPI.Unshipped.txt Declares new public APIs for client validation + new EnableClientValidation parameter.
src/Components/Forms/src/DataAnnotationsValidator.cs Enables SSR-only client validation by storing IClientValidationService in EditContext.Properties.
src/Components/Forms/src/ClientValidation/IClientValidationService.cs New public service contract for generating data-val-* attributes.
src/Components/Forms/src/ClientValidation/IClientValidationAdapter.cs New public extensibility interface for custom validation attributes.
src/Components/Forms/src/ClientValidation/DefaultClientValidationService.cs Default reflection-based generator with caching for supported validation attributes.
src/Components/Forms/src/ClientValidation/ClientValidationServiceCollectionExtensions.cs DI extension to register the default client validation service.
src/Components/Forms/src/ClientValidation/ClientValidationContext.cs Context passed to custom adapters for emitting attributes.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.

@oroztocil
oroztocil force-pushed the oroztocil/validation-client-side-dotnet branch from ae59ab2 to 0487e85 Compare April 24, 2026 13:50
@oroztocil
oroztocil force-pushed the oroztocil/validation-client-side-dotnet branch from 0487e85 to f6edaf0 Compare April 24, 2026 14:00
@oroztocil
oroztocil marked this pull request as ready for review April 24, 2026 14:00
@oroztocil
oroztocil requested a review from a team as a code owner April 24, 2026 14:00
@oroztocil oroztocil changed the title Add .NET support for client-side validation for Blazor SSR Add .NET support for client-side validation in Blazor SSR Apr 24, 2026

@dariatiurina dariatiurina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a few questions, but otherwise it looks amazing. Great job!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will we support custom IClientValidationService extensions? Should we delete this interface and just make the DefaultClientValidationService internal class?

@oroztocil oroztocil May 12, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need the type to be visible both in Components.Forms and Components.Web. Removing the interface would require the DefaultClientValidationService to be public which I'd argue is worse than having an interface which we don't expect others to implement. (Which might not be the case after all: someone might have a legitimate use case for generating metadata for client-side validation based on something else then the DataAnnotations attributes.)

@javiercn javiercn left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, some small pieces of feedback.

I would like us to re-consider how we can avoid putting this (render mode specific) code within Forms itself.

There is really no need for us to use the data-attributes on Blazor. We could emit a blob/component on to the page and have the library attach to the elements instead of reading the attributes from the elements themselves.

The whole point of this is to avoid having to sprinkle all this logic across the Input* components and avoid having this be part of the core Forms assembly.

{
// Cache keyed by model type + field name. Safe for concurrent access since the service
// is a singleton shared across requests. The computed dictionaries are immutable after creation.
private readonly ConcurrentDictionary<CacheKey, IReadOnlyDictionary<string, object>?> _cache = new();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are all this attributes not string,string? I would use a readonly struct with Name Value for clarity

@oroztocil oroztocil May 14, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This whole code path will go away when we do the "wire protocol" refactor so I would postpone this.


public IReadOnlyDictionary<string, object>? GetClientValidationAttributes(FieldIdentifier fieldIdentifier)
{
var cacheKey = (fieldIdentifier.Model.GetType(), fieldIdentifier.FieldName);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid records (can't find the definition for cachekey, but I suspect it's a record). We normally do ROS and implement equals/ghc as needed

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is not a record but alias for a tuple.

Comment on lines +102 to +115
// RangeAttribute lazily converts Minimum/Maximum from strings to the target type.
// Calling IsValid triggers this conversion so we can read the typed values.
// Wrap in try-catch to handle non-numeric operand types (e.g., DateTime ranges)
// which would throw when validating an integer value.
try
{
// TODO: Add support for DateTime ranges?
ra.IsValid(null);
}
catch (InvalidOperationException)
{
// Non-numeric range type - can't emit client-side attributes
break;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this what MVC does? Sounds kind of broken as opposed to a switch/case with the different possible numeric types? Maybe https://learn.microsoft.com/en-us/dotnet/standard/generics/math can be used?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MVC uses the same trick - it triggers the conversion from string to numeric types by calling IsValid(3). See

The difference is that it does not catch the exception for non-numeric values.

I replaced the try/catch block here with a type check:

    private static bool IsNumericRangeOperand(Type operandType)
        => operandType == typeof(int)
        || operandType == typeof(long)
        || operandType == typeof(short)
        || operandType == typeof(byte)
        || operandType == typeof(uint)
        || operandType == typeof(ulong)
        || operandType == typeof(ushort)
        || operandType == typeof(sbyte)
        || operandType == typeof(double)
        || operandType == typeof(float)
        || operandType == typeof(decimal);

The rule emit logic then uses this to skip unsupported range attributes. I think we could make dates work but I would suggest adding the support later.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this and all related client validation interfaces need to live in the Forms assembly? I would have expected these to live on Endpoints. They don't make sense elsewhere

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.

Comment on lines +220 to +226
private class CustomAdapterModel { [CustomValidation] public string Value { get; set; } = ""; }

private class CustomValidationAttribute : ValidationAttribute, IClientValidationAdapter
{
public IEnumerable<ClientValidationRule> GetClientValidationRules(string errorMessage)
=> [new ClientValidationRule("custom", errorMessage).WithParameter("param", "custom-value")];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants