CodexBloom - Programming Q&A Platform

advanced patterns When Using Custom Validations in ASP.NET Core 6 with FluentValidation

šŸ‘€ Views: 49 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-12
asp.net-core fluentvalidation validation C#

I recently switched to I've searched everywhere and can't find a clear answer..... Hey everyone, I'm running into an issue that's driving me crazy... I'm working with an scenario with custom validation logic in my ASP.NET Core 6 application using FluentValidation. I've created a validator for my model, but the validation is not firing as expected when I post the data to the API. Instead of returning the custom behavior messages, it's just returning the default ModelState errors. Here's my validator code: ```csharp public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(user => user.Email) .NotEmpty().WithMessage("Email is required.") .EmailAddress().WithMessage("Invalid email format."); RuleFor(user => user.Age) .GreaterThan(18).WithMessage("You must be at least 18 years old."); } } ``` I've registered the validator in `Startup.cs` like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<UserValidator>()); } ``` When I post invalid data like this: ```json { "Email": "invalid-email", "Age": 17 } ``` I expect to see custom behavior messages for both fields, but instead, the API response is: ```json { "errors": { "Email": ["The Email field is invalid."], "Age": ["The Age field must be a number."] } } ``` It seems like the validation is not picking up my custom messages. I've also tried explicitly setting `Validate()` on my controller action: ```csharp [HttpPost] public IActionResult CreateUser([FromBody] User user) { var result = _validator.Validate(user); if (!result.IsValid) { return BadRequest(result.Errors); } // Logic to save user } ``` But this still doesn't give me the custom validation messages. Is there an additional step I’m missing? Any guidance would be greatly appreciated! This is part of a larger API I'm building. Any ideas what could be causing this? Any ideas how to fix this? Any advice would be much appreciated. Any ideas how to fix this?