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

Open
wants to merge 31 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
d611b5c
Initial plan for issue
Copilot May 22, 2025
2d68f7a
Created project structure and moved source files
Copilot May 22, 2025
1b35c78
Complete implementation of validation APIs in separate package
Copilot May 22, 2025
4882df9
Remove type forwards and original validation code files
Copilot May 22, 2025
48391ab
Clean up some references
captainsafia May 22, 2025
3cb7c8e
Update trimmable projects for new package
captainsafia May 23, 2025
5d4305b
Update baselines
captainsafia May 23, 2025
e2eeed0
Fix build errors by regenerating project list files
Copilot May 27, 2025
eade235
Rerun GenerateProjectList
captainsafia May 30, 2025
18ab626
Update tests and snapshots
captainsafia Jun 12, 2025
4a053a3
Fix more tests
captainsafia Jun 12, 2025
f61aecb
Initial plan for issue
Copilot May 22, 2025
194ea8d
Use the unified validation instractructure for EditForm validation
oroztocil May 16, 2025
cc51880
Add EditForm validation sample
oroztocil May 16, 2025
5bcdeba
Add support for enumerable collections
oroztocil May 19, 2025
2ed691e
Add more complex demo
oroztocil May 19, 2025
4d0634f
Improve demo
oroztocil May 19, 2025
460e605
Suppress trimming warnings, refactor
oroztocil May 19, 2025
9cd6c5d
Add OnValidationError event to ValidateContext, use it to get field c…
oroztocil May 21, 2025
ccf29e5
Simplify the sample form
oroztocil May 21, 2025
5f8fb66
Update with rebased PR
javiercn Jun 11, 2025
fbad46f
Cleanup unused approach
javiercn Jun 12, 2025
2780feb
Remove sample changes
javiercn Jun 12, 2025
9500771
API cleanup
javiercn Jun 12, 2025
3b8e9b9
API changes
javiercn Jun 12, 2025
60a1cd4
Cleanup
javiercn Jun 12, 2025
a7f7330
Tests
javiercn Jun 12, 2025
c3a71e5
E2E test
javiercn Jun 12, 2025
a32f08a
Working
javiercn Jun 12, 2025
ef23cc4
Merge remote-tracking branch 'upstream/main' into oroztocil/unified-v…
maraf Jun 13, 2025
12bc8b8
Fix PublicAPI.Unshipped.txt
maraf Jun 13, 2025
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