dotnet / dotnet/aspnetcore

ValidationMessageStore.Add field accessor parameter shows a warning for nullable properties

Open
#41,338 5 comments 0 reactions 0 assignees View on GitHub
area-blazor bug feature-blazor-form-validation help wanted Pillar: Technical Debt Priority:2
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

Adding validation errors using the below `ValidationMessageStore.Add` method triggers a warning when nullable annotations are enabled for the project, and the property referenced in the `accessor` parameter has a nullable type.

https://github.com/dotnet/aspnetcore/blob/2f68ef8d42646046eb36ff2db5f17965a7893545/src/Components/Forms/src/ValidationMessageStore.cs#L38-L39

### Expected Behavior

No warnings are displayed for properties with nullable type.

### Steps To Reproduce

The following code shows how the warning message is triggered:

```csharp
private TestModel model = new();

private class TestModel
{
public string? Text { get; set; }
}

private void ManualValidation()
{
var messageStore = new ValidationMessageStore(editContext);

if (true /* External validation rule */)
{
messageStore?.Add(() => model.Text, "This value is not valid");
// ^^^^^^^^^^ <-- Warning triggered here
}
}
```

Full repro at https://github.com/vuorinem/aspnet_blazor_validationmessagestore_warning_repro/blob/6ba9b0a2b4fe0f38c1da6e7e5577dd75083dc9b6/BlazorApp1/Pages/Index.razor

### Exceptions (if any)

_No response_

### .NET Version

6.0.202

### Anything else?

Changing the method signature to the following (from ~~`object`~~ to generic parameter `TField`) could fix the issue as far as I understand:

```csharp
public void Add(Expression> accessor, string message)
```

That would match the the method in `FieldIdentifier`:

https://github.com/dotnet/aspnetcore/blob/2f68ef8d42646046eb36ff2db5f17965a7893545/src/Components/Forms/src/FieldIdentifier.cs#L20

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.