CodexBloom - Programming Q&A Platform

C# 10 - DataAnnotations Not Validating Nested Objects with FluentValidation in ASP.NET Core

👀 Views: 43 💬 Answers: 1 📅 Created: 2025-06-06
c# asp.net-core fluentvalidation datavalidation C#

I'm building a feature where I'm collaborating on a project where Could someone explain I'm working on a personal project and I'm working on a project and hit a roadblock. I'm encountering an issue with DataAnnotations not properly validating nested objects when using FluentValidation in an ASP.NET Core 6 application. I have a model with nested objects, and I'm trying to validate them using both DataAnnotations and FluentValidation. However, it seems that the validation for nested properties is being ignored entirely. Here’s a simplified version of my model: ```csharp public class Order { [Required] public string OrderId { get; set; } [Required] public Customer Customer { get; set; } } public class Customer { [Required] public string Name { get; set; } [EmailAddress] public string Email { get; set; } } ``` I have set up FluentValidation like this: ```csharp public class OrderValidator : AbstractValidator<Order> { public OrderValidator() { RuleFor(x => x.OrderId).NotEmpty(); RuleFor(x => x.Customer).NotNull(); RuleFor(x => x.Customer.Name).NotEmpty(); RuleFor(x => x.Customer.Email).EmailAddress(); } } ``` In my `Startup.cs`, I added the FluentValidation services: ```csharp services.AddControllers() .AddFluentValidation(f => f.RegisterValidatorsFromAssemblyContaining<OrderValidator>()); ``` However, when I submit a form without filling in the `Customer` properties, it only triggers validation for the `OrderId` and doesn't catch missing `Customer.Name` or `Customer.Email`. The model validation state shows that the nested properties are not being validated, and I don't see any errors in the response either. I’ve tried using `Validate` method explicitly on `Customer` in the controller action, but it still doesn’t apply the DataAnnotations. Here’s the action method: ```csharp [HttpPost] public IActionResult CreateOrder([FromBody] Order order) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // Process the order } ``` What am I missing here? Is there a specific configuration or approach I should follow to ensure that nested properties are validated correctly with FluentValidation in ASP.NET Core 6? How would you solve this? I'm working on a CLI tool that needs to handle this. I'd really appreciate any guidance on this. This issue appeared after updating to C# LTS. Has anyone else encountered this? My development environment is macOS. Any ideas how to fix this? Any feedback is welcome!