CodexBloom - Programming Q&A Platform

C# - implementing Custom Validation Logic in ASP.NET Core Model Binding Using FluentValidation

πŸ‘€ Views: 57 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-18
c# asp.net-core fluentvalidation C#

I'm working on a project and hit a roadblock. I'm currently working with scenarios with implementing custom validation logic in my ASP.NET Core application using FluentValidation. I've set up a model with various properties, and I want to ensure that some properties are conditionally validated based on the values of others. However, my validation logic doesn't seem to trigger as expected. For example, I have a model like this: ```csharp public class UserModel { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public string Email { get; set; } } ``` And my validator looks like this: ```csharp public class UserModelValidator : AbstractValidator<UserModel> { public UserModelValidator() { RuleFor(x => x.FirstName).NotEmpty(); RuleFor(x => x.LastName).NotEmpty(); RuleFor(x => x.Age) .GreaterThan(18) .When(x => !string.IsNullOrEmpty(x.Email)); } } ``` I expect the `Age` property to be validated only when `Email` is not null or empty. However, even when `Email` is empty, it still seems to validate the `Age` property correctly and does not return any errors when it is below 19. I've tried debugging and ensured that the validator is correctly registered in `Startup.cs`: ```csharp services.AddControllers() .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<UserModelValidator>()); ``` Additionally, I've confirmed that model validation is being triggered, but it doesn’t seem to adhere to the conditional logic I set up in the validator. I also tried using `.Unless` instead of `.When`, but that didn't help either. Could anyone point out what I'm missing or provide insights on how to appropriately set conditional validation rules using FluentValidation in this context? Any help would be greatly appreciated! I'm working with C# in a Docker container on Ubuntu 22.04. I've been using C# for about a year now. Am I missing something obvious?