Home > Mobile >  fluent validator in class library not work in asp.net core
fluent validator in class library not work in asp.net core

Time:09-06

when i put fluent validators in asp.net core client side validation project exactly work but when i put validator in class library not work

My model and validator in class library :

using FluentValidation;

namespace ClassLibrary1
{
    public class Person
    {
        public string Name { get; set; }
        public string Family { get; set; }
        public int Age { get; set; }
    }
    public class PersonValidator : AbstractValidator<Person>
    {
        public PersonValidator()
        {
            RuleFor(c => c.Name).NotEmpty().WithMessage("Name Is Empty");

        }
    }
}

In program.cs file :

services.AddFluentValidationAutoValidation(M =>
{
    M.DisableDataAnnotationsValidation = true;
}).AddFluentValidationClientsideAdapters()
  .AddValidatorsFromAssemblyContaining<PersonValidator>();

CodePudding user response:

I can't reproduce the issue, and it works in my side, I will show my test steps.

Steps

  1. my project structure.

    enter image description here

  2. The person.cs code same as yours

    enter image description here

  3. The program.cs code same as yours

    enter image description here

  4. My test method in Controller.

     [HttpPost]
     [Route("Test")]
     public IActionResult Test([FromBody]Person model)
     {
         if (!ModelState.IsValid) //<----Validate here
         {
             return new BadRequestObjectResult(ModelState);
         }
         return Ok();
         //Other Code..
     }
    
  5. Test result and it works.

    enter image description here

CodePudding user response:

thanks

i found solution

when class library is nullable the client side validation in asp.net core not work

solution :

1 : remove enable from *.csproj

2 : define nullable property [ public string? name{get;set}

  • Related