Home > Net >  C# FluentValidation not getting triggered
C# FluentValidation not getting triggered

Time:01-05

I have a class library with DTOs. For this DTOs I want to use FluentValidation to ensure that the inputs from the user are correct.

Example: I have a DTO named AddValidationDTO in my class library

namespace MYCoolProjApi.Model.DTOs.Validation {
    public class AddWstValidationDTO
    {
       public string? Name { get; set; }
       public string? Regex { get; set; }
       public string? AddedOrEditedBy { get; set; }
    }

    public class AddValidationDTOValidator : AbstractValidator<AddValidationDTO>
    {
       public WstAddValidationDTOValidator()
       {
          RuleFor(x => x.Name).NotNull().NotEmpty().WithMessage("Validation Name can't be null");
          RuleFor(x => x.Regex).NotNull().NotEmpty().WithMessage("Regex can't be null");
       }
    }
}

In my main project which is an ASP.NET Web Api I installed the FluentAPI Nuget package too and added this code to my Program.cs:

builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddFluentValidationClientsideAdapters();
builder.Services.AddValidatorsFromAssemblyContaining<AddValidationDTOValidator>();

When I send a request to the enpoint where a new Validation should be created with a faulty DTO I don't get an error and it gets saved to the database. This is the JSON which I send to the controller:

{
    "Name": "",
    "AddedOrEditedBy": "MyUser"
}

ValidationController:

[HttpPost("Add")]
public async Task<IActionResult> AddValidation([FromBody] AddValidationDTO validationDTO)
{
    await _validationService.AddValidation(validationDTO);
    return Ok();
}

CodePudding user response:

[HttpPost]
public IActionResult Create(ValidationDto dto) 
{
  if(! ModelState.IsValid) 
  { 
    // re-render the view when validation failed.
  }

 //do valid stuff
  return RedirectToAction("Index");
}

You add new class like:

public class ValidationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
            {
                //Do something you want
            }
        }
    }

and then add attribute to your action

[HttpPost]
[ValidationActionFilter]
public IActionResult Create(ValidationDto dto) 
{
...

Remember to register this if you are using DI

  • Related