-1

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>();

2 Answers2

0

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

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
0

I found the solution.

When the class library is nullable, the client-side validation in ASP.NET Core does not work.

Solution:

  1. Remove <Nullable>enable</Nullable> from the *.csproj

  2. Define nullable property:

    public string? name{get;set}
    
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77