Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/Components/Endpoints/src/Forms/ClientValidationCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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"):
Expand Down
76 changes: 58 additions & 18 deletions src/Components/Endpoints/src/Forms/DataAnnotationsLocalizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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('`');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we care about F# where backicks might be allowed as part of the type name?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Are you sure about backticks being allowed in type names? I thought backticks were used as escaping characters to allow spaces in type names. So the only backtick that we can encounter in run time Type.Name (for code that compiles) is the CLR arity. Spaces themselves are fine - the localization keys are plain strings, and include spaces.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I must be mis-remembering the identifier rule names of F# then 😄


return arityIndex < 0 ? name : name[..arityIndex];
}

private IStringLocalizer GetStringLocalizer(Type type, IStringLocalizerFactory localizerFactory)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,12 +173,9 @@ public void Localizer_LocalizesDisplayNameAndErrorMessage_OnMevPath()
var translations = new Dictionary<string, string>
{
["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(
Expand All @@ -198,11 +195,9 @@ public void Localizer_DoesNotLocalize_OnStaticValidatorPath()
var translations = new Dictionary<string, string>
{
["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<LocalizedFieldModel>(options, factory, nameof(LocalizedFieldModel.Field))!, nameof(LocalizedFieldModel.Field));
Expand All @@ -218,38 +213,29 @@ 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<Type, IDictionary<string, string>>
{
[typeof(InheritedFieldBaseModel)] = new Dictionary<string, string>
{
["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.
[typeof(DerivedFieldModel)] = new Dictionary<string, string>(),
};
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<DerivedFieldModel>(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);
}

Expand Down Expand Up @@ -465,7 +451,6 @@ private sealed record RuleData(
[property: JsonPropertyName("message")] string Message,
[property: JsonPropertyName("params")] Dictionary<string, string>? Params);

#pragma warning disable ASP0029 // Microsoft.Extensions.Validation evaluation APIs.
private static ValidationOptions CreateMevOptions(params Type[] validatableTypes)
{
var services = new ServiceCollection();
Expand All @@ -492,7 +477,6 @@ private static string[] GetMevValidatedPaths(ValidationOptions options, object m
typeInfo!.Validate(model, validateContext);
return validateContext.ValidationErrors?.Keys.ToArray() ?? Array.Empty<string>();
}
#pragma warning restore ASP0029

private sealed class TestStringLocalizerFactory(IDictionary<string, string> translations) : IStringLocalizerFactory
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -60,11 +58,9 @@ public DataAnnotationsEventSubscriptions(EditContext editContext, IServiceProvid
_serviceProvider = serviceProvider;
_messages = new ValidationMessageStore(_editContext);
_validationOptions = _serviceProvider?.GetService<IOptions<ValidationOptions>>()?.Value;
#pragma warning disable ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
_validatorTypeInfo = _validationOptions != null && _validationOptions.TryGetValidatableTypeInfo(_editContext.Model.GetType(), out var typeInfo)
? typeInfo
: null;
#pragma warning restore ASP0029 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
_editContext.OnFieldChanged += OnFieldChanged;
_editContext.OnValidationRequested += OnValidationRequested;

Expand All @@ -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))
Expand All @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -196,7 +188,6 @@ private void AddValidatorResults(List<ValidationResult> 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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 0 additions & 2 deletions src/Components/test/testassets/BasicTestApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<BasicTestApp.FormsTest.AsyncValidationGate>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,8 @@ public void ConfigureServices(IServiceCollection services)
}
services.AddSingleton<IStringLocalizerFactory>(
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<bool>("AllowLargeHubMessages"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

}
Original file line number Diff line number Diff line change
Expand Up @@ -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.")]
Expand Down
46 changes: 46 additions & 0 deletions src/Validation/gen/Templates/LocalizationHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}
}
Loading
Loading