Home > Software design >  FluentValidation.AspNetCore is not working in Web API project
FluentValidation.AspNetCore is not working in Web API project

Time:05-25

I am using nuget package FluentValidation.AspNetCore 11.0.1. I want to validate my model based on a condition for my endpoint. Added required code blocks as per the Fluent validation documentation, but still, my validation does not work.

I want to return a validation error when my model property contains letter "a" as in my validator class. Please check the below code blocks added to my project for validation.

Validator class

public class TestModelValidate : AbstractValidator<TestModel>
{
    public TestModelValidate()
    {
        RuleFor(t => t.Summary.ToString()).NotEmpty().NotNull().When(x => x.Summary.Contains("a")).WithMessage("Cannot be null");

    }

}

Startup class

Added below code block to ConfigureServices() method in Startup class.

 services.AddControllers().AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining<TestModelValidate>());

Model class

public class TestModel
{
   public string Summary { get; set; }
}

Controller class

 [HttpPost]
 public IActionResult Test(TestModel model)
 {
     if (!ModelState.IsValid) 
     {
          return new BadRequestObjectResult(ModelState);
     }

     return Ok("SUCCESS");
 }

I am passing following JSON object to the endpoint using Postman.

{
  "summary": "a"
}

Actual Result - SUCCESS

Expected Result - Validation Error

Appreciate, your help!

CodePudding user response:

If you want to use ModelState.IsValid we can try to set ApiBehaviorOptions.SuppressModelStateInvalidFilter be true.

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});

I think you can try to use Must with the condition !x.Contains("a") to judge your logic.

public class TestModelValidate : AbstractValidator<TestModel>
{
    public TestModelValidate()
    {
        RuleFor(t => t.Summary).NotEmpty().NotNull().WithMessage("Cannot be null")
                               .Must(x => !x.Contains("a")).WithMessage("Can't contain a");
    }
}
  • Related