Skip to content

Use the unified validation API for Blazor forms #62045

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Components/Components.slnf
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,11 @@
"src\\StaticAssets\\src\\Microsoft.AspNetCore.StaticAssets.csproj",
"src\\StaticAssets\\test\\Microsoft.AspNetCore.StaticAssets.Tests.csproj",
"src\\Testing\\src\\Microsoft.AspNetCore.InternalTesting.csproj",
"src\\Validation\\gen\\Microsoft.Extensions.Validation.ValidationsGenerator.csproj",
"src\\Validation\\src\\Microsoft.Extensions.Validation.csproj",
"src\\Validation\\test\\Microsoft.Extensions.Validation.GeneratorTests\\Microsoft.Extensions.Validation.GeneratorTests.csproj",
"src\\Validation\\test\\Microsoft.Extensions.Validation.Tests\\Microsoft.Extensions.Validation.Tests.csproj",
"src\\WebEncoders\\src\\Microsoft.Extensions.WebEncoders.csproj"
]
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Validation;

[assembly: MetadataUpdateHandler(typeof(Microsoft.AspNetCore.Components.Forms.EditContextDataAnnotationsExtensions))]

Expand All @@ -15,7 +18,7 @@ namespace Microsoft.AspNetCore.Components.Forms;
/// <summary>
/// Extension methods to add DataAnnotations validation to an <see cref="EditContext"/>.
/// </summary>
public static class EditContextDataAnnotationsExtensions
public static partial class EditContextDataAnnotationsExtensions
{
/// <summary>
/// Adds DataAnnotations validation support to the <see cref="EditContext"/>.
Expand Down Expand Up @@ -59,20 +62,31 @@ private static void ClearCache(Type[]? _)
}
#pragma warning restore IDE0051 // Remove unused private members

private sealed class DataAnnotationsEventSubscriptions : IDisposable
private sealed partial class DataAnnotationsEventSubscriptions : IDisposable
{
private static readonly ConcurrentDictionary<(Type ModelType, string FieldName), PropertyInfo?> _propertyInfoCache = new();

private readonly EditContext _editContext;
private readonly IServiceProvider? _serviceProvider;
private readonly ValidationMessageStore _messages;
private readonly ValidationOptions? _validationOptions;
#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
private readonly IValidatableInfo? _validatorTypeInfo;
#pragma warning restore ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
private readonly Dictionary<string, FieldIdentifier> _validationPathToFieldIdentifierMapping = new();

[UnconditionalSuppressMessage("Trimming", "IL2066", Justification = "Model types are expected to be defined in assemblies that do not get trimmed.")]
public DataAnnotationsEventSubscriptions(EditContext editContext, IServiceProvider serviceProvider)
{
_editContext = editContext ?? throw new ArgumentNullException(nameof(editContext));
_serviceProvider = serviceProvider;
_messages = new ValidationMessageStore(_editContext);

_validationOptions = _serviceProvider?.GetService<IOptions<ValidationOptions>>()?.Value;
#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
_validatorTypeInfo = _validationOptions != null && _validationOptions.TryGetValidatableTypeInfo(_editContext.Model.GetType(), out var typeInfo)
? typeInfo
: null;
#pragma warning restore ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
_editContext.OnFieldChanged += OnFieldChanged;
_editContext.OnValidationRequested += OnValidationRequested;

Expand Down Expand Up @@ -112,6 +126,18 @@ private void OnFieldChanged(object? sender, FieldChangedEventArgs eventArgs)
private void OnValidationRequested(object? sender, ValidationRequestedEventArgs e)
{
var validationContext = new ValidationContext(_editContext.Model, _serviceProvider, items: null);

if (!TryValidateTypeInfo(validationContext))
{
ValidateWithDefaultValidator(validationContext);
}

_editContext.NotifyValidationStateChanged();
}

[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Model types are expected to be defined in assemblies that do not get trimmed.")]
private void ValidateWithDefaultValidator(ValidationContext validationContext)
{
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(_editContext.Model, validationContext, validationResults, true);

Expand All @@ -136,8 +162,62 @@ private void OnValidationRequested(object? sender, ValidationRequestedEventArgs
_messages.Add(new FieldIdentifier(_editContext.Model, fieldName: string.Empty), validationResult.ErrorMessage!);
}
}
}

_editContext.NotifyValidationStateChanged();
#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
private bool TryValidateTypeInfo(ValidationContext validationContext)
{
if (_validatorTypeInfo is null)
{
return false;
}

var validateContext = new ValidateContext
{
ValidationOptions = _validationOptions!,
ValidationContext = validationContext,
};
try
{
validateContext.OnValidationError += AddMapping;

var validationTask = _validatorTypeInfo.ValidateAsync(_editContext.Model, validateContext, CancellationToken.None);
if (!validationTask.IsCompleted)
{
throw new InvalidOperationException("Async validation is not supported");
}

var validationErrors = validateContext.ValidationErrors;

// Transfer results to the ValidationMessageStore
_messages.Clear();

if (validationErrors is not null && validationErrors.Count > 0)
{
foreach (var (fieldKey, messages) in validationErrors)
{
var fieldIdentifier = _validationPathToFieldIdentifierMapping[fieldKey];
_messages.Add(fieldIdentifier, messages);
}
}
}
catch (Exception)
{
throw;
}
finally
{
validateContext.OnValidationError -= AddMapping;
_validationPathToFieldIdentifierMapping.Clear();
}

return true;

}
private void AddMapping(ValidationErrorContext context)
{
_validationPathToFieldIdentifierMapping[context.Path] =
new FieldIdentifier(context.Container ?? _editContext.Model, context.Name);
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Components" />
<Reference Include="Microsoft.Extensions.Validation" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!--
Skip building and running the Components E2E tests in CI unless explicitly configured otherwise via
EXECUTE_COMPONENTS_E2E_TESTS. At least build the Components E2E tests locally unless SkipTestBuild is set.
-->
<_BuildAndTest>false</_BuildAndTest>
<_BuildAndTest
Condition=" '$(ContinuousIntegrationBuild)' == 'true' AND '$(EXECUTE_COMPONENTS_E2E_TESTS)' == 'true' ">true</_BuildAndTest>
<_BuildAndTest
Condition=" '$(ContinuousIntegrationBuild)' != 'true' AND '$(SkipTestBuild)' != 'true' ">true</_BuildAndTest>
<_BuildAndTest Condition=" '$(ContinuousIntegrationBuild)' == 'true' AND '$(EXECUTE_COMPONENTS_E2E_TESTS)' == 'true' ">true</_BuildAndTest>
<_BuildAndTest Condition=" '$(ContinuousIntegrationBuild)' != 'true' AND '$(SkipTestBuild)' != 'true' ">true</_BuildAndTest>
<ExcludeFromBuild Condition=" !$(_BuildAndTest) ">true</ExcludeFromBuild>
<SkipTests Condition=" !$(_BuildAndTest) ">true</SkipTests>

Expand Down Expand Up @@ -67,39 +65,19 @@
</ItemGroup>

<ItemGroup Condition="'$(TestTrimmedOrMultithreadingApps)' == 'true'">
<ProjectReference Include="..\..\benchmarkapps\Wasm.Performance\TestApp\Wasm.Performance.TestApp.csproj"
Targets="Build;Publish"
Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\Wasm.Performance.TestApp\" />

<ProjectReference
Include="..\testassets\BasicTestApp\BasicTestApp.csproj"
Targets="Build;Publish"
Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\BasicTestApp\" />

<ProjectReference
Include="..\testassets\GlobalizationWasmApp\GlobalizationWasmApp.csproj"
Targets="Build;Publish"
Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\GlobalizationWasmApp\;" />

<ProjectReference
Include="..\..\WebAssembly\testassets\StandaloneApp\StandaloneApp.csproj"
Targets="Build;Publish"
Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\StandaloneApp\;" />

<ProjectReference
Include="..\..\WebAssembly\testassets\Wasm.Prerendered.Server\Wasm.Prerendered.Server.csproj"
Targets="Build;Publish"
Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\Wasm.Prerendered.Server\;" />

<ProjectReference
Include="..\..\WebAssembly\testassets\ThreadingApp\ThreadingApp.csproj"
Targets="Build;Publish"
Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=false;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\ThreadingApp\;" />

<ProjectReference
Include="..\testassets\Components.TestServer\Components.TestServer.csproj"
Targets="Build;Publish"
Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\Components.TestServer\;" />
<ProjectReference Include="..\..\benchmarkapps\Wasm.Performance\TestApp\Wasm.Performance.TestApp.csproj" Targets="Build;Publish" Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\Wasm.Performance.TestApp\" />

<ProjectReference Include="..\testassets\BasicTestApp\BasicTestApp.csproj" Targets="Build;Publish" Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\BasicTestApp\" />

<ProjectReference Include="..\testassets\GlobalizationWasmApp\GlobalizationWasmApp.csproj" Targets="Build;Publish" Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\GlobalizationWasmApp\;" />

<ProjectReference Include="..\..\WebAssembly\testassets\StandaloneApp\StandaloneApp.csproj" Targets="Build;Publish" Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\StandaloneApp\;" />

<ProjectReference Include="..\..\WebAssembly\testassets\Wasm.Prerendered.Server\Wasm.Prerendered.Server.csproj" Targets="Build;Publish" Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\Wasm.Prerendered.Server\;" />

<ProjectReference Include="..\..\WebAssembly\testassets\ThreadingApp\ThreadingApp.csproj" Targets="Build;Publish" Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=false;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\ThreadingApp\;" />

<ProjectReference Include="..\testassets\Components.TestServer\Components.TestServer.csproj" Targets="Build;Publish" Properties="BuildProjectReferences=false;TestTrimmedOrMultithreadingApps=true;PublishDir=$(MSBuildThisFileDirectory)$(OutputPath)trimmed-or-threading\Components.TestServer\;" />
</ItemGroup>

<!-- Shared testing infrastructure for running E2E tests using selenium -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Text;
using Components.TestServer.RazorComponents;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.E2ETesting;
using OpenQA.Selenium;
using TestServer;
using Xunit.Abstractions;

namespace Microsoft.AspNetCore.Components.E2ETests.ServerRenderingTests;

public class AddValidationIntegrationTest : ServerTestBase<BasicTestAppServerSiteFixture<RazorComponentEndpointsStartup<Root>>>
{
public AddValidationIntegrationTest(BrowserFixture browserFixture, BasicTestAppServerSiteFixture<RazorComponentEndpointsStartup<Root>> serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output)
{
}

protected override void InitializeAsyncCore()
{
Navigate("subdir/forms/add-validation-form");
Browser.Exists(By.Id("is-interactive"));
}

[Fact]
public void FormWithNestedValidation_Works()
{
Browser.Exists(By.Id("submit-form")).Click();

Browser.Exists(By.Id("is-invalid"));

// Validation summary
var messageElements = Browser.FindElements(By.CssSelector(".validation-errors > .validation-message"));

var messages = messageElements.Select(element => element.Text)
.ToList();

var expected = new[]
{
"Order Name is required.",
"Full Name is required.",
"Email is required.",
"Street is required.",
"Zip Code is required.",
"Product Name is required."
};

Assert.Equal(expected, messages);

// Individual field messages
var individual = Browser.FindElements(By.CssSelector(".mb-3 > .validation-message"))
.Select(element => element.Text)
.ToList();

Assert.Equal(expected, individual);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

<PropertyGroup>
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
Expand All @@ -11,6 +11,9 @@

<!-- Project supports more than one language -->
<BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>

<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>

</PropertyGroup>

<PropertyGroup Condition="'$(TestTrimmedOrMultithreadingApps)' == 'true'">
Expand Down Expand Up @@ -47,10 +50,8 @@
<ItemGroup>
<ResolvedFileToPublish RelativePath="$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('subdir\subdir', 'subdir').Replace('subdir/subdir', 'subdir'))" />

<ResolvedFileToPublish
Include="@(ResolvedFileToPublish)"
RelativePath="$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('subdir\_content', '_content').Replace('subdir/subdir', '_content'))"
Condition="$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('subdir\_content', 'subdir/_content').Contains('subdir/_content'))" />
<ResolvedFileToPublish Include="@(ResolvedFileToPublish)" RelativePath="$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('subdir\_content', '_content').Replace('subdir/subdir', '_content'))" Condition="$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Replace('subdir\_content', 'subdir/_content').Contains('subdir/_content'))" />

</ItemGroup>
</Target>

Expand Down
3 changes: 3 additions & 0 deletions src/Components/test/testassets/BasicTestApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ public static async Task Main(string[] args)
await SimulateErrorsIfNeededForTest();

var builder = WebAssemblyHostBuilder.CreateDefault(args);

builder.Services.AddValidation();

builder.RootComponents.Add<HeadOutlet>("head::after");
builder.RootComponents.Add<Index>("root");
builder.RootComponents.RegisterForJavaScript<DynamicallyAddedRootComponent>("my-dynamic-root-component");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@
<Nullable>annotations</Nullable>
<RazorLangVersion>latest</RazorLangVersion>
<BlazorRoutingEnableRegexConstraint>true</BlazorRoutingEnableRegexConstraint>
<InterceptorsNamespaces>$(InterceptorsNamespaces);Microsoft.AspNetCore.Http.Validation.Generated;Microsoft.Extensions.Validation.Generated</InterceptorsNamespaces>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="$(RepoRoot)/src/Validation/gen/Microsoft.Extensions.Validation.ValidationsGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

<ItemGroup>
<Reference Include="Microsoft.AspNetCore" />
<Reference Include="Microsoft.AspNetCore.Authentication.Cookies" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public RazorComponentEndpointsStartup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddValidation();

services.AddRazorComponents(options =>
{
options.MaxFormMappingErrorCount = 10;
Expand Down
Loading
Loading