CodexBloom - Programming Q&A Platform

How to implement guide with fluentvalidation - custom validation rule not triggering for nested properties in .net 6

👀 Views: 41 💬 Answers: 1 📅 Created: 2025-06-24
fluentvalidation .net6 validation C#

I've looked through the documentation and I'm still confused about I'm using FluentValidation in a .NET 6 application to validate a complex model that has nested properties. I have defined a custom validation rule for a property within a nested object, but it doesn't seem to trigger as expected. Here’s a simplified version of my model: ```csharp public class User { public string Name { get; set; } public Address Address { get; set; } } public class Address { public string City { get; set; } public string PostalCode { get; set; } } ``` And here’s my validator: ```csharp public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(user => user.Address) .NotNull() .DependentRules(() => { RuleFor(user => user.Address.City) .NotEmpty().WithMessage("City must not be empty."); }); } } ``` When I try to validate a `User` instance where the `Address` is null, the custom rule for `City` doesn't seem to trigger. I expected it to validate `City` only if `Address` is not null, but it appears to skip the nested validation entirely when `Address` is null. Here’s how I'm performing the validation: ```csharp var user = new User { Name = "John Doe", Address = null }; var validator = new UserValidator(); var result = validator.Validate(user); if (!result.IsValid) { foreach (var behavior in result.Errors) { Console.WriteLine(behavior.ErrorMessage); } } ``` The output only indicates that the `Address` is null and does not mention anything about the `City`. I’ve confirmed that the fluent validation library is properly installed (version 10.3.0). I’m uncertain if my approach to handling nested properties is correct. Could anyone provide insight on why the validation for `City` isn’t firing in this case? Is there a different pattern I should follow to ensure that nested properties are validated even when their parent object might be null? Any help would be greatly appreciated!