Blazored / FluentValidation

A library for using FluentValidation with Blazor
https://blazored.github.io/FluentValidation/
MIT License
588 stars 85 forks source link

[Bug] Discrepancy between Web API + FluentValidation and Blazor + Blazored.FluentValidation when validating deeply nested child properties #84

Closed icnocop closed 2 years ago

icnocop commented 3 years ago

Hi.

Thank you for Blazored.FluentValidation! 🙏

Description I'm seeing a discrepancy when validating a model with deeply nested child properties in Blazored.FluentValidation when compared to using FluentValidation in a Web API controller.

Blazored.FluentValidation doesn't seem to automatically pick up the validation rules for the deeply nested child properties.

To Reproduce Steps to reproduce the behavior:

  1. Clone the repo at https://github.com/icnocop/BlazoredFluentValidation.
  2. Set BlazorServer as the Startup Project.
  3. Run the project.
  4. Click on the Validate button.
  5. Notice the validation error messages:
    • 'Age' must be greater than '0'.
    • 'Name' must not be empty.
  6. Now, make a POST request to /api/Pets with the following JSON body:
    {
    "Address": { }
    }
  7. Notice the response with validation error message:
    {
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|86f990a0-4b7f30a1df18614a.",
    "errors": {
        "Age": [
            "'Age' must be greater than '0'."
        ],
        "Name": [
            "'Name' must not be empty."
        ],
        "Address.Street": [
            "'Street' must not be empty."
        ]
    }
    }

Expected behavior I expected Blazored.FluentValidation to display the validation error message • 'Street' must not be empty..

Screenshots HTTP POST using Postman for example: image

Hosting Model I've only tested with Blazor Server.

Additional context In Startup.cs, I'm automatically registering validators and implicitly validating child properties:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddFluentValidation(fv =>
    {
        fv.RegisterValidatorsFromAssemblyContaining<Startup>();
        fv.ImplicitlyValidateChildProperties = true;
    });

    ...
}

Similar to https://github.com/Blazored/FluentValidation/issues/82#issuecomment-914898397, to work-around this issue, I have to explicitly set the validator on the child property by un-commenting the code on line 20 in .\samples\BlazorServer\Models\Pet.cs.

Thank you! 🙏

chrissainty commented 2 years ago

Hi @icnocop, I've been looking into this and noticed that this feature of FluentValidation relies on some MVC infrastructure to work and is only available in MVC applications. Based on this I'm going to close this issue.