2

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!

2 Answers 2

3

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

In my case the solution with SuppressModelStateInvalidFilter = true doesn't works.

I'm using .NET 6 and FluentValidation.AspNetCore 11.3.0 then I need to inject using AddValidatorsFromAssemblyContaining before registering controllers with builder.Services.AddControllers();

Example:

{...}
builder.Services.AddValidatorsFromAssemblyContaining<AddProductCommandValidator>();
builder.Services.AddControllers();
{...}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.