dotnet / dotnet/runtime

[OptionsValidator] Source Generator for [Range] Ignores ErrorMessage and DisplayName

Open
#123,137 5 comments 1 reaction 0 assignees View on GitHub
area-Extensions-Options source-generator
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

I have the below
```C#
#pragma warning disable ASP0029
[ValidatableType]
#pragma warning restore ASP0029
public class WeatherForecast
{
public int? Id { get; set; }
public required DateTime Date { get; set; }

[Range(-20, 55, ErrorMessage = "Temperature must be between -20 and 55.")]
public required int TemperatureC { get; set; }

[Required(ErrorMessage = "Summary is required.")]
public string? Summary { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

[ValidateObjectMembers]
public SubWeatherForecast SubWeather { get; set; } = new();
}

#pragma warning disable ASP0029
[ValidatableType]
#pragma warning restore ASP0029
public class SubWeatherForecast
{
[Required(ErrorMessage = "Name is required.")]
public string? Name { get; set; }
}

[OptionsValidator]
public partial class WeatherForecastValidator : IValidateOptions
{
}

[OptionsValidator]
public partial class SubWeatherForecastValidator : IValidateOptions
{
}
```

When this is triggered through Minimal API I get the correct error message of Temperature must be between -20 and 55.

However, when I execute through:

```C#
var validator = new WeatherForecastValidator();

var result = validator.Validate(null, weatherForecast);
```

The error message reverts to default "The field WeatherForecast.TemperatureC must be between -20 and 55."

When I do the same thing with `[Required(ErrorMessage = "Summary is required.")]` it works correctly.

In addition when validating with Minimal API default the key on the sub class is correctly SubWeather.Name but when processing with validator.Validate the key is cut off and it is only "Name"

### Reproduction Steps

Use the Dot Net 10 template, use minimal api end point, include builder.Services.Validation(). On the end point .DisableValidation(), then

```C#
var validator = new WeatherForecastValidator();
var result = validator.Validate(null, weatherForecast);
```

### Expected behavior

validator.Validate(null, weatherForecast); is processed in the same way that Minimal API is processed.

### Actual behavior

The ErrorMessage in [Range] is not respected with validator.Validate and sub classes cut off the name of the key.

### Regression?

_No response_

### Known Workarounds

Don't use validator.Validate.

### Configuration

_No response_

### Other information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.