diff --git a/src/Components/Endpoints/src/Forms/ClientValidationCache.cs b/src/Components/Endpoints/src/Forms/ClientValidationCache.cs index a963f1f6960e..9ca6a6bf06b7 100644 --- a/src/Components/Endpoints/src/Forms/ClientValidationCache.cs +++ b/src/Components/Endpoints/src/Forms/ClientValidationCache.cs @@ -91,7 +91,6 @@ private bool IsServerValidatable( } } -#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. private bool IsFieldValidatedByMev(Type formType, string renderedName) { var path = GetModelRelativePath(renderedName); @@ -128,7 +127,6 @@ internal bool HasValidatableTypeInfo(Type type) => _validationOptions.Resolvers.Count > 0 && _typeHasValidatableInfo.GetOrAdd(type, key => _validationOptions.TryGetValidatableTypeInfo(key, out _)); -#pragma warning restore ASP0029 // Derives the field's property-name path relative to the form model from the rendered HTML name. // The rendered name is the binder key "{modelPrefix}.{path}" (e.g. "Person.Address.Street"): diff --git a/src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs b/src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs index 19affdcd681d..2b9eb0ec33bb 100644 --- a/src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs +++ b/src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs @@ -43,7 +43,7 @@ public string ResolveDisplayName(in ClientValidationFieldMetadata metadata, bool // Keep in sync with the generated ResolveAttributeErrorMessage/FormatErrorMessage in // src/Validation/gen/Templates/ValidatableInfo.cs, which this mirrors for the SSR client payload. public string? ResolveAttributeErrorMessage( - string memberName, + string? memberName, string displayName, Type type, ValidationAttribute attribute, @@ -54,38 +54,78 @@ public string ResolveDisplayName(in ClientValidationFieldMetadata metadata, bool return attribute.FormatErrorMessage(displayName); } - var lookupKey = GetErrorMessageKey(attribute, memberName, type); - - if (string.IsNullOrEmpty(lookupKey)) - { - return attribute.FormatErrorMessage(displayName); - } - var localizer = GetStringLocalizer(type, localizerFactory); - var localizedTemplate = localizer[lookupKey]; + var localizedTemplate = FindLocalizedTemplate(localizer, attribute, memberName, type); - if (localizedTemplate.ResourceNotFound) + if (localizedTemplate is null) { return attribute.FormatErrorMessage(displayName); } // Format the localized template with attribute-specific arguments - return FormatMessage(attribute, CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatMessage(attribute, CultureInfo.CurrentCulture, localizedTemplate, displayName); } - private string? GetErrorMessageKey(ValidationAttribute attribute, string memberName, Type type) + // Resolves the localized message template for a validation attribute. + // + // An explicit ErrorMessage is used verbatim as the lookup key. Otherwise the built-in key + // convention is applied, walking from the most specific key to the least specific one: + // + // {DeclaringType}_{MemberName}_{AttributeType}_Error + // {DeclaringType}_{AttributeType}_Error + // {AttributeType}_Error + // + // Returns null when no key resolves, in which case the caller falls back to the + // non-localized message produced by the attribute itself. + // + // Keep in sync with the generated LocalizationHelpers.FindLocalizedTemplate in + // src/Validation/gen/Templates/LocalizationHelpers.cs. + private static string? FindLocalizedTemplate( + IStringLocalizer localizer, + ValidationAttribute attribute, + string? memberName, + Type declaringType) { if (!string.IsNullOrEmpty(attribute.ErrorMessage)) { - return attribute.ErrorMessage; + var explicitMatch = localizer[attribute.ErrorMessage]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + // The member-specific tier is skipped when there is no member to key on, which is the case + // for a type-level attribute that reports no member names. + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } } - return options.MessageKeyProvider?.Invoke(new ValidationMessageKeyContext + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = type, - }); + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(Type type) + { + var name = (Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; } private IStringLocalizer GetStringLocalizer(Type type, IStringLocalizerFactory localizerFactory) diff --git a/src/Components/Endpoints/test/FormValidation/ClientValidationProviderTests.cs b/src/Components/Endpoints/test/FormValidation/ClientValidationProviderTests.cs index 4e271b311a2f..d05b4b673890 100644 --- a/src/Components/Endpoints/test/FormValidation/ClientValidationProviderTests.cs +++ b/src/Components/Endpoints/test/FormValidation/ClientValidationProviderTests.cs @@ -173,12 +173,9 @@ public void Localizer_LocalizesDisplayNameAndErrorMessage_OnMevPath() var translations = new Dictionary { ["Custom Label"] = "Étiquette", - ["req-key"] = "{0} est requis.", + ["LocalizedFieldModel_Field_RequiredAttribute_Error"] = "{0} est requis.", }; var options = CreateMevOptions(typeof(LocalizedFieldModel)); -#pragma warning disable ASP0029 // Microsoft.Extensions.Validation evaluation APIs. - options.MessageKeyProvider = _ => "req-key"; -#pragma warning restore ASP0029 var factory = new TestStringLocalizerFactory(translations); var rule = SingleRule( @@ -198,11 +195,9 @@ public void Localizer_DoesNotLocalize_OnStaticValidatorPath() var translations = new Dictionary { ["Custom Label"] = "Étiquette", - ["req-key"] = "{0} est requis.", + ["LocalizedFieldModel_Field_RequiredAttribute_Error"] = "{0} est requis.", }; -#pragma warning disable ASP0029 // Microsoft.Extensions.Validation evaluation APIs. - var options = new ValidationOptions { MessageKeyProvider = _ => "req-key" }; -#pragma warning restore ASP0029 + var options = new ValidationOptions(); var factory = new TestStringLocalizerFactory(translations); var rule = SingleRule(GetData(options, factory, nameof(LocalizedFieldModel.Field))!, nameof(LocalizedFieldModel.Field)); @@ -218,14 +213,15 @@ public void Localizer_ResolvesFromDeclaringType_ForInheritedProperty() // The validated property is declared on the base type but the form model is the derived type. // Server-side validation resolves the localizer, message key, and display name from the // *declaring* type, so the client payload must do the same rather than use the derived - // (runtime container) type. The factory only knows translations for the base type, so a - // localized result proves the declaring type flowed through. + // (runtime container) type. The factory only knows translations for the base type, and the + // conventional key itself is built from the base type name, so a localized result proves the + // declaring type flowed through both the localizer lookup and the key convention. var byType = new Dictionary> { [typeof(InheritedFieldBaseModel)] = new Dictionary { ["Base Label"] = "Étiquette", - ["req-key"] = "{0} est requis.", + ["InheritedFieldBaseModel_Field_RequiredAttribute_Error"] = "{0} est requis.", }, // The derived type has no translations; if it were (incorrectly) used, both the display // name and the message template would fall back to their non-localized values. @@ -233,23 +229,13 @@ public void Localizer_ResolvesFromDeclaringType_ForInheritedProperty() }; var factory = new TypeAwareStringLocalizerFactory(byType); - Type? messageKeyDeclaringType = null; var options = CreateMevOptions(typeof(DerivedFieldModel)); -#pragma warning disable ASP0029 // Microsoft.Extensions.Validation evaluation APIs. - options.MessageKeyProvider = context => - { - messageKeyDeclaringType = context.DeclaringType; - return "req-key"; - }; -#pragma warning restore ASP0029 var rule = SingleRule( GetMevData(options, factory, (nameof(DerivedFieldModel.Field), "Model." + nameof(DerivedFieldModel.Field)))!, "Model." + nameof(DerivedFieldModel.Field)); - // The declaring (base) type is used for the message key context... - Assert.Equal(typeof(InheritedFieldBaseModel), messageKeyDeclaringType); - // ...and for both the display-name and error-message localizer lookups. + // The declaring (base) type is used for both the display-name and error-message lookups. Assert.Equal("Étiquette est requis.", rule.Message); } @@ -465,7 +451,6 @@ private sealed record RuleData( [property: JsonPropertyName("message")] string Message, [property: JsonPropertyName("params")] Dictionary? Params); -#pragma warning disable ASP0029 // Microsoft.Extensions.Validation evaluation APIs. private static ValidationOptions CreateMevOptions(params Type[] validatableTypes) { var services = new ServiceCollection(); @@ -492,7 +477,6 @@ private static string[] GetMevValidatedPaths(ValidationOptions options, object m typeInfo!.Validate(model, validateContext); return validateContext.ValidationErrors?.Keys.ToArray() ?? Array.Empty(); } -#pragma warning restore ASP0029 private sealed class TestStringLocalizerFactory(IDictionary translations) : IStringLocalizerFactory { diff --git a/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs b/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs index 582b7638478e..c6fa34c6d6d1 100644 --- a/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs +++ b/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs @@ -49,9 +49,7 @@ private sealed partial class DataAnnotationsEventSubscriptions : IDisposable 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 IValidatableTypeInfo? _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. [UnconditionalSuppressMessage("Trimming", "IL2066", Justification = "Model types are expected to be defined in assemblies that do not get trimmed.")] public DataAnnotationsEventSubscriptions(EditContext editContext, IServiceProvider serviceProvider) @@ -60,11 +58,9 @@ public DataAnnotationsEventSubscriptions(EditContext editContext, IServiceProvid _serviceProvider = serviceProvider; _messages = new ValidationMessageStore(_editContext); _validationOptions = _serviceProvider?.GetService>()?.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; @@ -80,7 +76,6 @@ private void OnFieldChanged(object? sender, FieldChangedEventArgs eventArgs) var fieldIdentifier = eventArgs.FieldIdentifier; var modelType = fieldIdentifier.Model.GetType(); -#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. if (_validationOptions is not null && _validationOptions.TryGetValidatableTypeInfo(modelType, out var typeInfo) && typeInfo.TryFindProperty(fieldIdentifier.FieldName, _validationOptions, out var validatablePropertyInfo)) @@ -89,7 +84,6 @@ private void OnFieldChanged(object? sender, FieldChangedEventArgs eventArgs) fieldIdentifier, token => ValidateFieldWithValidatableInfoAsync(fieldIdentifier, validatablePropertyInfo, token)); } -#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. else if (TryGetValidatableProperty(fieldIdentifier, out var propertyInfo)) { _editContext.RegisterAsyncFieldValidator( @@ -112,7 +106,6 @@ private void OnValidationRequested(object? sender, ValidationRequestedEventArgs } } -#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 async Task ValidateFormAndNotifyAsync(CancellationToken cancellationToken) { if (_validatorTypeInfo is not null) @@ -140,7 +133,6 @@ private void ValidateFormAndNotify() _editContext.NotifyValidationStateChanged(); } -#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. [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Model types are expected to be defined in assemblies that do not get trimmed.")] private async Task ValidateFormWithValidatorAsync(CancellationToken cancellationToken) @@ -196,7 +188,6 @@ private void AddValidatorResults(List validationResults) } } -#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. [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Model types are expected to be defined in assemblies that do not get trimmed.")] private async Task ValidateFormWithValidatableInfoAsync(IValidatableTypeInfo validatableInfo, CancellationToken cancellationToken) { diff --git a/src/Components/Forms/test/EditContextValidatableInfoFieldTest.cs b/src/Components/Forms/test/EditContextValidatableInfoFieldTest.cs index 91853dbdb195..40e2ba98057a 100644 --- a/src/Components/Forms/test/EditContextValidatableInfoFieldTest.cs +++ b/src/Components/Forms/test/EditContextValidatableInfoFieldTest.cs @@ -3,8 +3,6 @@ #nullable enable -#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. - using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Components.Test.Helpers; using Microsoft.Extensions.DependencyInjection; diff --git a/src/Components/test/testassets/BasicTestApp/FormsTest/AsyncDataAnnotationsModels.cs b/src/Components/test/testassets/BasicTestApp/FormsTest/AsyncDataAnnotationsModels.cs index 9f093c15eb0a..15029f26065c 100644 --- a/src/Components/test/testassets/BasicTestApp/FormsTest/AsyncDataAnnotationsModels.cs +++ b/src/Components/test/testassets/BasicTestApp/FormsTest/AsyncDataAnnotationsModels.cs @@ -14,8 +14,6 @@ using Microsoft.Extensions.Options; using Microsoft.Extensions.Validation; -#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. - namespace BasicTestApp.FormsTest; // Async per-field validation attribute used by the DataAnnotations async E2E components. diff --git a/src/Components/test/testassets/BasicTestApp/Program.cs b/src/Components/test/testassets/BasicTestApp/Program.cs index b5ef7a33f96d..66b0ad80266f 100644 --- a/src/Components/test/testassets/BasicTestApp/Program.cs +++ b/src/Components/test/testassets/BasicTestApp/Program.cs @@ -24,9 +24,7 @@ public static async Task Main(string[] args) var builder = WebAssemblyHostBuilder.CreateDefault(args); -#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. builder.Services.AddValidation(); -#pragma warning restore ASP0029 // Interactive host registers the gate so the async validation E2E tests control settling deterministically. builder.Services.AddSingleton(); diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs b/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs index dbe2318a0631..f7ea724f174d 100644 --- a/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs +++ b/src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsStartup.cs @@ -53,10 +53,8 @@ public void ConfigureServices(IServiceCollection services) } services.AddSingleton( new TestStringLocalizerFactory(ClientValidationLocalizationData.Translations)); -#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. services.AddValidation(options => options.Resolvers.Add(new BasicTestApp.FormsTest.AsyncValidationResolver())); -#pragma warning restore ASP0029 // Increase 10 MB hub message limit (default 32 KB) if (Configuration.GetValue("AllowLargeHubMessages")) diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/CustomerModel.cs b/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/CustomerModel.cs index 94606771bff2..0125d2c2d837 100644 --- a/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/CustomerModel.cs +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/CustomerModel.cs @@ -17,9 +17,7 @@ public class CustomerModel public AddressModel PaymentAddress { get; set; } = new AddressModel(); -#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. [SkipValidation] -#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. public AddressModel ShippingAddress { get; set; } = new AddressModel(); } diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/OrderModel.cs b/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/OrderModel.cs index f4bfcd55af50..e698ca92b18a 100644 --- a/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/OrderModel.cs +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/ValidationModels/OrderModel.cs @@ -4,9 +4,8 @@ using System.ComponentModel.DataAnnotations; namespace BasicTestApp.ValidationModels; -#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. + [Microsoft.Extensions.Validation.ValidatableType] -#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. public class OrderModel { [Required(ErrorMessage = "Order Name is required.")] diff --git a/src/Validation/gen/Templates/LocalizationHelpers.cs b/src/Validation/gen/Templates/LocalizationHelpers.cs index 47ebab904924..a362997de9c2 100644 --- a/src/Validation/gen/Templates/LocalizationHelpers.cs +++ b/src/Validation/gen/Templates/LocalizationHelpers.cs @@ -7,4 +7,50 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } diff --git a/src/Validation/gen/Templates/ValidatableInfo.cs b/src/Validation/gen/Templates/ValidatableInfo.cs index ab86d41100db..58a195d950ec 100644 --- a/src/Validation/gen/Templates/ValidatableInfo.cs +++ b/src/Validation/gen/Templates/ValidatableInfo.cs @@ -69,7 +69,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -85,34 +85,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, diff --git a/src/Validation/gen/Templates/ValidatableTypeInfo.cs b/src/Validation/gen/Templates/ValidatableTypeInfo.cs index ba11c1c10fa1..45f47af19840 100644 --- a/src/Validation/gen/Templates/ValidatableTypeInfo.cs +++ b/src/Validation/gen/Templates/ValidatableTypeInfo.cs @@ -365,7 +365,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/src/PublicAPI.Unshipped.txt b/src/Validation/src/PublicAPI.Unshipped.txt index 7e293127be09..ab952a550de0 100644 --- a/src/Validation/src/PublicAPI.Unshipped.txt +++ b/src/Validation/src/PublicAPI.Unshipped.txt @@ -34,18 +34,8 @@ Microsoft.Extensions.Validation.ValidateContext.ServiceProvider.get -> System.IS Microsoft.Extensions.Validation.ValidateContext.ServiceProvider.init -> void Microsoft.Extensions.Validation.ValidateContext.ValidationErrors.get -> System.Collections.Generic.IReadOnlyDictionary!>? Microsoft.Extensions.Validation.ValidateContext.ValidationOptions.init -> void -Microsoft.Extensions.Validation.ValidationMessageKeyContext -Microsoft.Extensions.Validation.ValidationMessageKeyContext.DeclaringType.get -> System.Type! -Microsoft.Extensions.Validation.ValidationMessageKeyContext.DeclaringType.init -> void -Microsoft.Extensions.Validation.ValidationMessageKeyContext.MemberName.get -> string! -Microsoft.Extensions.Validation.ValidationMessageKeyContext.MemberName.init -> void -Microsoft.Extensions.Validation.ValidationMessageKeyContext.ValidationMessageKeyContext() -> void -Microsoft.Extensions.Validation.ValidationMessageKeyContext.ValidatorType.get -> System.Type! -Microsoft.Extensions.Validation.ValidationMessageKeyContext.ValidatorType.init -> void Microsoft.Extensions.Validation.ValidationOptions.LocalizerProvider.get -> System.Func! Microsoft.Extensions.Validation.ValidationOptions.LocalizerProvider.set -> void -Microsoft.Extensions.Validation.ValidationOptions.MessageKeyProvider.get -> System.Func? -Microsoft.Extensions.Validation.ValidationOptions.MessageKeyProvider.set -> void Microsoft.Extensions.Validation.ValidationOptions.TryGetValidatableParameterInfo(System.Reflection.ParameterInfo! parameterInfo, out Microsoft.Extensions.Validation.IValidatableParameterInfo? validatableInfo) -> bool Microsoft.Extensions.Validation.ValidationOptions.TryGetValidatableTypeInfo(System.Type! type, out Microsoft.Extensions.Validation.IValidatableTypeInfo? validatableTypeInfo) -> bool *REMOVED*abstract Microsoft.Extensions.Validation.ValidatableParameterInfo.GetValidationAttributes() -> System.ComponentModel.DataAnnotations.ValidationAttribute![]! diff --git a/src/Validation/src/ValidationMessageKeyContext.cs b/src/Validation/src/ValidationMessageKeyContext.cs deleted file mode 100644 index 2fdf142929e3..000000000000 --- a/src/Validation/src/ValidationMessageKeyContext.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace Microsoft.Extensions.Validation; - -/// -/// Provides contextual information used to compute the resource key for looking up a localized -/// validation error message. -/// -/// -/// An instance is passed to when a custom key -/// convention is configured. The returned key is then resolved against the configured -/// . -/// -public sealed class ValidationMessageKeyContext -{ - /// - /// Gets the type of the validator that produced the error being localized. For DataAnnotations, - /// this is the validation attribute type (for example, typeof(RequiredAttribute)). - /// - public required Type ValidatorType { get; init; } - - /// - /// Gets the name of the member being validated: the property name for property validation, the - /// parameter name for parameter validation, or the type name for type-level validation. - /// - public required string MemberName { get; init; } - - /// - /// Gets the type associated with the member being validated: the containing type for a property, - /// the validated type itself for type-level validation, or the parameter's own type for a parameter. - /// - public required Type DeclaringType { get; init; } -} diff --git a/src/Validation/src/ValidationOptions.cs b/src/Validation/src/ValidationOptions.cs index d35350df0db8..07d9d3c93b74 100644 --- a/src/Validation/src/ValidationOptions.cs +++ b/src/Validation/src/ValidationOptions.cs @@ -45,18 +45,6 @@ public class ValidationOptions public Func LocalizerProvider { get; set; } = (type, factory) => factory.Create(type); - /// - /// Gets or sets a delegate that computes the resource key used to look up a localized validation - /// message. - /// - /// - /// The provider supplies the lookup key by convention (for example, keyed by - /// ) for validators that do not specify an - /// explicit message. When a validator specifies an explicit message, that message is used as the - /// lookup key and the provider is not consulted. - /// - public Func? MessageKeyProvider { get; set; } - /// /// Attempts to get validation information for the specified type. /// diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs index 9317a5c66053..738f8dd38f76 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs @@ -309,6 +309,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -383,7 +429,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -399,34 +445,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1034,7 +1063,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs index 9317a5c66053..738f8dd38f76 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.ParameterDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs @@ -309,6 +309,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -383,7 +429,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -399,34 +445,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1034,7 +1063,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeResourceTypeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeResourceTypeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs index 7a0b20e9dade..a601477bbb15 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeResourceTypeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeResourceTypeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs index fad6d39374ea..43bd4d63d736 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_DisplayAttributeTakesPrecedenceOverDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithControlCharacters_EmitsValidLiteral#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithControlCharacters_EmitsValidLiteral#ValidatableInfoResolver.g.verified.cs index c627d7084fc0..566a83a580ff 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithControlCharacters_EmitsValidLiteral#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithControlCharacters_EmitsValidLiteral#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs index 853edfc29dee..48568ae8a9f2 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs index d68b2a59e4e9..85be0f2e98ce 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs index 8d631ddb4bb4..b12dbb65a0b3 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType_OnHiddenGenericProperty#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType_OnHiddenGenericProperty#ValidatableInfoResolver.g.verified.cs index c13082a727eb..4c4fc6a0e1b6 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType_OnHiddenGenericProperty#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithResourceType_OnHiddenGenericProperty#ValidatableInfoResolver.g.verified.cs @@ -334,6 +334,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -408,7 +454,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -424,34 +470,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1059,7 +1088,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithoutDisplayAttribute_UsesPropertyName#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithoutDisplayAttribute_UsesPropertyName#ValidatableInfoResolver.g.verified.cs index c56af96e56ea..4d247472cadc 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithoutDisplayAttribute_UsesPropertyName#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.PropertyDisplayName_WithoutDisplayAttribute_UsesPropertyName#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_LiteralOnConstructorParameter#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_LiteralOnConstructorParameter#ValidatableInfoResolver.g.verified.cs index dcdc58eaedf7..a4d31b0d6716 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_LiteralOnConstructorParameter#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_LiteralOnConstructorParameter#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs index fdbbfd176d6d..1f2bd6e487fb 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs index d4ed50318028..79362e388f93 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.RecordPropertyDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs index 72a0cedc12f7..e988067e083d 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithDisplayNameAttribute#ValidatableInfoResolver.g.verified.cs @@ -318,6 +318,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -392,7 +438,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -408,34 +454,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1043,7 +1072,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs index c5835716f8c4..f6ecec27f544 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithNameOnly#ValidatableInfoResolver.g.verified.cs @@ -318,6 +318,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -392,7 +438,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -408,34 +454,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1043,7 +1072,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs index 695eed15c3ed..d3634eeda64d 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorDisplayNameTests.TypeDisplayName_WithResourceType#ValidatableInfoResolver.g.verified.cs @@ -318,6 +318,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -392,7 +438,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -408,34 +454,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1043,7 +1072,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanGenerateWhenAddValidationCalledMultipleTimes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanGenerateWhenAddValidationCalledMultipleTimes#ValidatableInfoResolver.g.verified.cs index bb6a3eaae4cd..5381c6307003 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanGenerateWhenAddValidationCalledMultipleTimes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanGenerateWhenAddValidationCalledMultipleTimes#ValidatableInfoResolver.g.verified.cs @@ -326,6 +326,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -400,7 +446,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -416,34 +462,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1051,7 +1080,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateClassTypesWithAttribute#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateClassTypesWithAttribute#ValidatableInfoResolver.g.verified.cs index 0372351bd36e..7274d1f89e51 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateClassTypesWithAttribute#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateClassTypesWithAttribute#ValidatableInfoResolver.g.verified.cs @@ -405,6 +405,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -479,7 +525,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -495,34 +541,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1130,7 +1159,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs index 2e99c9f892f6..859da17c993f 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypes#ValidatableInfoResolver.g.verified.cs @@ -411,6 +411,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -485,7 +531,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -501,34 +547,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1136,7 +1165,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypesWithJsonIgnore#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypesWithJsonIgnore#ValidatableInfoResolver.g.verified.cs index 62208b72990d..0892fed967d1 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypesWithJsonIgnore#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateComplexTypesWithJsonIgnore#ValidatableInfoResolver.g.verified.cs @@ -341,6 +341,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -415,7 +461,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -431,34 +477,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1066,7 +1095,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs index 6b845d81bd92..d1863fb06562 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject#ValidatableInfoResolver.g.verified.cs @@ -362,6 +362,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -436,7 +482,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -452,34 +498,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1087,7 +1116,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject_WithoutPropertyValidations#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject_WithoutPropertyValidations#ValidatableInfoResolver.g.verified.cs index 8686a4076ff9..03fe0a1a650b 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject_WithoutPropertyValidations#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateIValidatableObject_WithoutPropertyValidations#ValidatableInfoResolver.g.verified.cs @@ -368,6 +368,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -442,7 +488,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -458,34 +504,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1093,7 +1122,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateMultipleNamespaces#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateMultipleNamespaces#ValidatableInfoResolver.g.verified.cs index dc343d5bba59..fa3e2f9d4c7a 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateMultipleNamespaces#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateMultipleNamespaces#ValidatableInfoResolver.g.verified.cs @@ -341,6 +341,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -415,7 +461,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -431,34 +477,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1066,7 +1095,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs index 122ceeea89e5..57522b123b12 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParameters#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParametersFromDelegateVariableHandler#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParametersFromDelegateVariableHandler#ValidatableInfoResolver.g.verified.cs index 9efb51d42b05..894b5a447581 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParametersFromDelegateVariableHandler#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateParametersFromDelegateVariableHandler#ValidatableInfoResolver.g.verified.cs @@ -331,6 +331,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -405,7 +451,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -421,34 +467,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1056,7 +1085,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs index 4f6e75b15e47..0493b5203ff0 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidatePolymorphicTypes#ValidatableInfoResolver.g.verified.cs @@ -394,6 +394,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -468,7 +514,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -484,34 +530,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1119,7 +1148,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordStructTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordStructTypes#ValidatableInfoResolver.g.verified.cs index d857eefe276c..416519c4f45c 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordStructTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordStructTypes#ValidatableInfoResolver.g.verified.cs @@ -359,6 +359,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -433,7 +479,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -449,34 +495,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1084,7 +1113,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs index 5c9122188aa9..dd722fe85d71 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypes#ValidatableInfoResolver.g.verified.cs @@ -439,6 +439,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -513,7 +559,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -529,34 +575,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1164,7 +1193,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypesWithAttribute#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypesWithAttribute#ValidatableInfoResolver.g.verified.cs index 0372351bd36e..7274d1f89e51 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypesWithAttribute#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecordTypesWithAttribute#ValidatableInfoResolver.g.verified.cs @@ -405,6 +405,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -479,7 +525,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -495,34 +541,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1130,7 +1159,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs index 1c0e08db958e..bbecb5442adf 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateRecursiveTypes#ValidatableInfoResolver.g.verified.cs @@ -331,6 +331,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -405,7 +451,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -421,34 +467,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1056,7 +1085,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs index 1ac700621fc2..1a97df2da680 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateTypeWithParsableProperties#ValidatableInfoResolver.g.verified.cs @@ -373,6 +373,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -447,7 +493,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -463,34 +509,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1098,7 +1127,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateValidationAttributesOnClasses#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateValidationAttributesOnClasses#ValidatableInfoResolver.g.verified.cs index f14260dcec03..8b4023320f1d 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateValidationAttributesOnClasses#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.CanValidateValidationAttributesOnClasses#ValidatableInfoResolver.g.verified.cs @@ -346,6 +346,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -420,7 +466,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -436,34 +482,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1071,7 +1100,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs index 8b20db0a3c88..4fc89d553b17 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmitForExemptTypes#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnClassProperties#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnClassProperties#ValidatableInfoResolver.g.verified.cs index 59c0b47a940c..4af37b34a03f 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnClassProperties#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnClassProperties#ValidatableInfoResolver.g.verified.cs @@ -385,6 +385,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -459,7 +505,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -475,34 +521,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1110,7 +1139,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnEndpointParameters#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnEndpointParameters#ValidatableInfoResolver.g.verified.cs index 8b20db0a3c88..4fc89d553b17 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnEndpointParameters#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnEndpointParameters#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnRecordProperties#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnRecordProperties#ValidatableInfoResolver.g.verified.cs index e986954efd51..0778df987784 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnRecordProperties#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.DoesNotEmit_ForSkipValidationAttribute_OnRecordProperties#ValidatableInfoResolver.g.verified.cs @@ -341,6 +341,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -415,7 +461,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -431,34 +477,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1066,7 +1095,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.IValidatableObject_ReceivesValidatedInstanceAsObjectInstance#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.IValidatableObject_ReceivesValidatedInstanceAsObjectInstance#ValidatableInfoResolver.g.verified.cs index 8dd51d5495ac..346449be91a7 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.IValidatableObject_ReceivesValidatedInstanceAsObjectInstance#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.IValidatableObject_ReceivesValidatedInstanceAsObjectInstance#ValidatableInfoResolver.g.verified.cs @@ -318,6 +318,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -392,7 +438,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -408,34 +454,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1043,7 +1072,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsClassesWithNonAccessibleTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsClassesWithNonAccessibleTypes#ValidatableInfoResolver.g.verified.cs index bf9026d54b91..134efbd369bd 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsClassesWithNonAccessibleTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsClassesWithNonAccessibleTypes#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsFileLocalTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsFileLocalTypes#ValidatableInfoResolver.g.verified.cs index 9317a5c66053..738f8dd38f76 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsFileLocalTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsFileLocalTypes#ValidatableInfoResolver.g.verified.cs @@ -309,6 +309,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -383,7 +429,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -399,34 +445,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1034,7 +1063,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsIndexerPropertiesOnTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsIndexerPropertiesOnTypes#ValidatableInfoResolver.g.verified.cs index 6ff2ca3b265e..1166f4462cc0 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsIndexerPropertiesOnTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsIndexerPropertiesOnTypes#ValidatableInfoResolver.g.verified.cs @@ -325,6 +325,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -399,7 +445,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -415,34 +461,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1050,7 +1079,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsNonReadableAndStaticProperties#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsNonReadableAndStaticProperties#ValidatableInfoResolver.g.verified.cs index 70f1c43eccac..7e60f6a2ac3e 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsNonReadableAndStaticProperties#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.SkipsNonReadableAndStaticProperties#ValidatableInfoResolver.g.verified.cs @@ -347,6 +347,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -421,7 +467,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -437,34 +483,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1072,7 +1101,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesInternalTypes#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesInternalTypes#ValidatableInfoResolver.g.verified.cs index 8b54e31865cd..0ca3d1b9d651 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesInternalTypes#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesInternalTypes#ValidatableInfoResolver.g.verified.cs @@ -347,6 +347,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -421,7 +467,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -437,34 +483,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1072,7 +1101,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesPropertiesWithJsonIgnoreWhenWritingConditions#ValidatableInfoResolver.g.verified.cs b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesPropertiesWithJsonIgnoreWhenWritingConditions#ValidatableInfoResolver.g.verified.cs index 4de9caaa00a1..6408041d9b8a 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesPropertiesWithJsonIgnoreWhenWritingConditions#ValidatableInfoResolver.g.verified.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/snapshots/ValidationsGeneratorTests.ValidatesPropertiesWithJsonIgnoreWhenWritingConditions#ValidatableInfoResolver.g.verified.cs @@ -337,6 +337,52 @@ file static class LocalizationHelpers => context.ValidationOptions.LocalizerProvider(type, factory) ?? throw new global::System.InvalidOperationException( $"The ValidationOptions.LocalizerProvider delegate returned null for type '{type.FullName}'. The delegate must return a non-null IStringLocalizer instance."); + + public static string? FindLocalizedTemplate( + global::Microsoft.Extensions.Localization.IStringLocalizer localizer, + global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, + string? memberName, + global::System.Type declaringType) + { + if (!string.IsNullOrEmpty(attribute.ErrorMessage)) + { + var explicitMatch = localizer[attribute.ErrorMessage!]; + if (!explicitMatch.ResourceNotFound) + { + return explicitMatch.Value; + } + } + + var attributeName = attribute.GetType().Name; + var typeName = GetKeySegment(declaringType); + + if (memberName is not null) + { + var memberMatch = localizer[$"{typeName}_{memberName}_{attributeName}_Error"]; + if (!memberMatch.ResourceNotFound) + { + return memberMatch.Value; + } + } + + var typeMatch = localizer[$"{typeName}_{attributeName}_Error"]; + if (!typeMatch.ResourceNotFound) + { + return typeMatch.Value; + } + + var globalMatch = localizer[$"{attributeName}_Error"]; + + return globalMatch.ResourceNotFound ? null : globalMatch.Value; + } + + private static string GetKeySegment(global::System.Type type) + { + var name = (global::System.Nullable.GetUnderlyingType(type) ?? type).Name; + var arityIndex = name.IndexOf('`'); + + return arityIndex < 0 ? name : name[..arityIndex]; + } } @@ -411,7 +457,7 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo private protected static string? ResolveAttributeErrorMessage( global::Microsoft.Extensions.Validation.ValidateContext context, - string memberName, + string? memberName, string displayName, global::System.Type declaringType, global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, @@ -427,34 +473,17 @@ private protected static bool TryGetRequiredAttribute(global::System.ComponentMo return result.ErrorMessage; } - var lookupKey = !string.IsNullOrEmpty(attribute.ErrorMessage) - ? attribute.ErrorMessage - : context.ValidationOptions.MessageKeyProvider?.Invoke(new global::Microsoft.Extensions.Validation.ValidationMessageKeyContext - { - ValidatorType = attribute.GetType(), - MemberName = memberName, - DeclaringType = declaringType, - }); - - if (string.IsNullOrEmpty(lookupKey)) - { - return result.ErrorMessage; - } - var localizer = LocalizationHelpers.CreateStringLocalizer(context, declaringType, localizerFactory); - var localizedTemplate = localizer[lookupKey!]; - if (localizedTemplate.ResourceNotFound) + var localizedTemplate = LocalizationHelpers.FindLocalizedTemplate(localizer, attribute, memberName, declaringType); + if (localizedTemplate is null) { return result.ErrorMessage; } - return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate.Value, displayName); + return FormatErrorMessage(attribute, global::System.Globalization.CultureInfo.CurrentCulture, localizedTemplate, displayName); } - // Keep in sync with DataAnnotationsLocalizer.FormatMessage in - // src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs, which mirrors this switch for the - // Blazor SSR client-validation payload. private static string FormatErrorMessage( global::System.ComponentModel.DataAnnotations.ValidationAttribute attribute, global::System.Globalization.CultureInfo culture, @@ -1062,7 +1091,7 @@ private protected override void ReportError(global::Microsoft.Extensions.Validat // If no member names are specified, then treat this as a top-level error var errorMessage = ResolveAttributeErrorMessage( context, - memberName: Type.Name, + memberName: null, displayName, declaringType: Type, attribute, diff --git a/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidationLocalizationIntegrationTests.cs b/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidationLocalizationIntegrationTests.cs index daa764ad274d..ff63fc4aa0e6 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidationLocalizationIntegrationTests.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidationLocalizationIntegrationTests.cs @@ -10,8 +10,8 @@ namespace Microsoft.Extensions.Validation.Tests; // End-to-end coverage for the validation localization pipeline that is now emitted into the -// generated code and driven purely by ValidationOptions.LocalizerProvider / MessageKeyProvider and a -// registered IStringLocalizerFactory. +// generated code and driven purely by ValidationOptions.LocalizerProvider, the built-in message +// key convention, and a registered IStringLocalizerFactory. public class ValidationLocalizationIntegrationTests : ValidationTestBase { [Theory] @@ -67,8 +67,8 @@ public async Task Property_WithLocalizer_LocalizesDisplayNameAndErrorMessage(boo [InlineData(false)] public async Task Property_LookupMiss_FallsBackToAttributeErrorMessage(bool useAsync) { - // Factory is present but the key is not translated, so the message produced by the attribute - // (here, the raw ErrorMessage used as the lookup key) is used as the fallback. + // Factory is present but neither the explicit key nor any conventional key is translated, + // so the message produced by the attribute is used as the fallback. var (provider, options) = CreateServices(new Dictionary()); var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); var context = GeneratedValidationTestHelpers.CreateContext(provider, options); @@ -117,15 +117,53 @@ public async Task Property_SelfFormattingAttribute_UsesFormatMessageHook(bool us [Theory] [InlineData(true)] [InlineData(false)] - public async Task Property_MessageKeyProvider_ComputesLookupKey(bool useAsync) + public async Task Property_ConventionKey_MemberTier_TakesPrecedence(bool useAsync) { + // All three conventional keys resolve, so the most specific one wins. var translations = new Dictionary { - ["RequiredAttribute"] = "{0} is mandatory.", + ["LocalizedDefaultModel_Name_RequiredAttribute_Error"] = "{0} is required for this member.", + ["LocalizedDefaultModel_RequiredAttribute_Error"] = "{0} is required for this type.", + ["RequiredAttribute_Error"] = "{0} is mandatory.", }; - var (provider, options) = CreateServices( - translations, - o => o.MessageKeyProvider = ctx => ctx.ValidatorType.Name); + var (provider, options) = CreateServices(translations); + var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(typeInfo, new LocalizedDefaultModel(), context, useAsync, default); + + Assert.Equal("Name is required for this member.", Single(context, "Name")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Property_ConventionKey_TypeTier_UsedWhenMemberKeyMissing(bool useAsync) + { + var translations = new Dictionary + { + ["LocalizedDefaultModel_RequiredAttribute_Error"] = "{0} is required for this type.", + ["RequiredAttribute_Error"] = "{0} is mandatory.", + }; + var (provider, options) = CreateServices(translations); + var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(typeInfo, new LocalizedDefaultModel(), context, useAsync, default); + + Assert.Equal("Name is required for this type.", Single(context, "Name")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Property_ConventionKey_GlobalTier_UsedWhenSpecificKeysMissing(bool useAsync) + { + var translations = new Dictionary + { + ["RequiredAttribute_Error"] = "{0} is mandatory.", + }; + var (provider, options) = CreateServices(translations); var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); var context = GeneratedValidationTestHelpers.CreateContext(provider, options); @@ -137,28 +175,104 @@ public async Task Property_MessageKeyProvider_ComputesLookupKey(bool useAsync) [Theory] [InlineData(true)] [InlineData(false)] - public async Task Property_ExplicitErrorMessage_WinsOverProvider(bool useAsync) + public async Task Property_ConventionKey_NoMatch_FallsBackToAttributeMessage(bool useAsync) { - // An explicit ErrorMessage on the validator is used as the key directly; the convention - // provider is not consulted. + // A factory is registered but no conventional key resolves, so the attribute's own + // non-localized message is used. var translations = new Dictionary { - ["RequiredKey"] = "Explicit {0}.", - ["ConventionKey"] = "Convention {0}.", + ["UnrelatedKey"] = "unused", + }; + var (provider, options) = CreateServices(translations); + var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(typeInfo, new LocalizedDefaultModel(), context, useAsync, default); + + Assert.Equal("The Name field is required.", Single(context, "Name")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task TypeLevelAttribute_WithoutMemberNames_SkipsMemberTier(bool useAsync) + { + // A type-level attribute that reports no member names has no member to key on, so the + // member tier is skipped rather than repeating the type name in the key. + var translations = new Dictionary + { + ["LocalizedTypeLevelModel_LocalizedTypeLevelModel_AlwaysFailsAttribute_Error"] = "doubled key", + ["LocalizedTypeLevelModel_AlwaysFailsAttribute_Error"] = "{0} failed type-level validation.", }; - var providerCalled = false; - var (provider, options) = CreateServices(translations, o => o.MessageKeyProvider = _ => + var (provider, options) = CreateServices(translations); + var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(typeInfo, new LocalizedTypeLevelModel(), context, useAsync, default); + + Assert.Equal("LocalizedTypeLevelModel failed type-level validation.", Single(context, string.Empty)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Property_ExplicitErrorMessage_WinsOverConvention(bool useAsync) + { + // An explicit ErrorMessage on the validator is used as the key directly and takes + // precedence over the built-in convention when it resolves. + var translations = new Dictionary { - providerCalled = true; - return "ConventionKey"; - }); + ["RequiredKey"] = "Explicit {0}.", + ["LocalizedKeyedModel_Name_RequiredAttribute_Error"] = "Convention {0}.", + ["RequiredAttribute_Error"] = "Convention {0}.", + }; + var (provider, options) = CreateServices(translations); var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); var context = GeneratedValidationTestHelpers.CreateContext(provider, options); await ValidateAsync(typeInfo, new LocalizedKeyedModel(), context, useAsync, default); Assert.Equal("Explicit Customer Name.", Single(context, "Name")); - Assert.False(providerCalled); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Property_ExplicitErrorMessageMiss_FallsThroughToConvention(bool useAsync) + { + // The explicit ErrorMessage is not a known resource key, so the lookup falls through to the + // conventional keys rather than giving up on localization. + var translations = new Dictionary + { + ["LocalizedKeyedModel_Name_RequiredAttribute_Error"] = "Convention {0}.", + }; + var (provider, options) = CreateServices(translations); + var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(typeInfo, new LocalizedKeyedModel(), context, useAsync, default); + + Assert.Equal("Convention Customer Name.", Single(context, "Name")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Property_AttributeWithBuiltInDefaultMessage_UsesConvention(bool useAsync) + { + // Several built-in attributes expose a non-null ErrorMessage holding their own default + // message even when the developer never set one. The convention must still reach them. + var translations = new Dictionary + { + ["EmailAddressAttribute_Error"] = "{0} is not a valid address.", + }; + var (provider, options) = CreateServices(translations); + var typeInfo = GeneratedValidationTestHelpers.GetTypeInfo(options); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(typeInfo, new LocalizedDefaultMessageModel { Email = "not-an-email" }, context, useAsync, default); + + Assert.Equal("Email is not a valid address.", Single(context, "Email")); } [Theory] @@ -273,6 +387,79 @@ public async Task Parameter_LocalizerProvider_InvokedWithParameterType_AndUsed(b Assert.Equal("The Nom du paramètre field is required.", Single(context, "value")); } + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Parameter_ConventionKey_IncludesParameterTypeSegment(bool useAsync) + { + // A top-level parameter has no declaring type, so the parameter's own type supplies the + // type segment and is kept in the key just like any other declaring type. + var translations = new Dictionary + { + ["String_value_RequiredAttribute_Error"] = "{0} is required for this parameter.", + ["String_RequiredAttribute_Error"] = "{0} is required for this type.", + ["RequiredAttribute_Error"] = "{0} is mandatory.", + }; + var (provider, options) = CreateServices(translations); + var parameterInfo = typeof(LocalizedParameterActions) + .GetMethod(nameof(LocalizedParameterActions.Action))! + .GetParameters()[0]; + Assert.True(options.TryGetValidatableParameterInfo(parameterInfo, out var paramInfo)); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(paramInfo, null, context, useAsync, default); + + Assert.Equal("Parameter Name is required for this parameter.", Single(context, "value")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Parameter_ConventionKey_UnwrapsNullableValueType(bool useAsync) + { + // A nullable value type contributes its underlying type as the key segment, so int? and int + // share the same keys instead of every nullable collapsing onto "Nullable". + var translations = new Dictionary + { + ["Nullable_count_RangeAttribute_Error"] = "wrapper-typed key", + ["Nullable_RangeAttribute_Error"] = "wrapper-typed key", + ["Int32_count_RangeAttribute_Error"] = "{0} is out of range for this parameter.", + }; + var (provider, options) = CreateServices(translations); + var parameterInfo = typeof(LocalizedParameterActions) + .GetMethod(nameof(LocalizedParameterActions.NullableAction))! + .GetParameters()[0]; + Assert.True(options.TryGetValidatableParameterInfo(parameterInfo, out var paramInfo)); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(paramInfo, 42, context, useAsync, default); + + Assert.Equal("count is out of range for this parameter.", Single(context, "count")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Parameter_ConventionKey_StripsGenericArityFromTypeSegment(bool useAsync) + { + // A generic type contributes its name without the arity marker, so the key stays typeable + // in a resx and all closed constructions share it. + var translations = new Dictionary + { + ["LocalizedWrapper_value_RequiredAttribute_Error"] = "{0} is required for this parameter.", + }; + var (provider, options) = CreateServices(translations); + var parameterInfo = typeof(LocalizedParameterActions) + .GetMethod(nameof(LocalizedParameterActions.GenericAction))! + .GetParameters()[0]; + Assert.True(options.TryGetValidatableParameterInfo(parameterInfo, out var paramInfo)); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + await ValidateAsync(paramInfo, null, context, useAsync, default); + + Assert.Equal("value is required for this parameter.", Single(context, "value")); + } + private static string Single(ValidateContext context, string key) => Assert.Single(context.ValidationErrors![key].Select(e => e.ErrorMessage)); @@ -348,6 +535,31 @@ public class LocalizedSelfFormattingModel public string? Value { get; set; } } +[ValidatableType] +[AlwaysFails] +public class LocalizedTypeLevelModel +{ + public string? Value { get; set; } +} + +[ValidatableType] +public class LocalizedDefaultMessageModel +{ + [EmailAddress] + public string? Email { get; set; } +} + +public class LocalizedWrapper +{ + public T? Value { get; set; } +} + +[AttributeUsage(AttributeTargets.Class)] +public sealed class AlwaysFailsAttribute : ValidationAttribute +{ + public override bool IsValid(object? value) => false; +} + [ValidatableType] public class LocalizedResourceErrorModel { @@ -383,6 +595,10 @@ public IEnumerable Validate(ValidationContext validationContex public static class LocalizedParameterActions { public static void Action([Display(Name = "Parameter Name")][Required] string? value) { } + + public static void NullableAction([Range(1, 10)] int? count) { } + + public static void GenericAction([Required] LocalizedWrapper? value) { } } [AttributeUsage(AttributeTargets.Property)]