Search code examples
c#asp.net-mvcvalidationautofacfluentvalidation

FluentValidation not using my Rules


I'm using FluentValidation with Autofac and ValidatorFactoryBase

When I execute my project my Validator is executed, but when I send a post my rules not is used but the current validator is my own Validator.

My Validator:

public class UsuarioCadastrarValidator : AbstractValidator<UsuarioCadastrarVM>
{
    public UsuarioCadastrarValidator()
    {
        RuleFor(a => a.Nome).NotEmpty().WithMessage("Campo obrigatório");

        RuleFor(a => a.Nome).Length(4, 200).WithMessage("Digite seu nome completo");
    }
}

My Model:

public class UsuarioCadastrarVM
{
    public string Nome { get; set; }
    public int CargoId { get; set; }
}

Global.asax(Works well):

...
    FluentValidationModelValidatorProvider.Configure();


            var assembly = Assembly.GetExecutingAssembly();

            builder.RegisterAssemblyTypes(assembly)
                   .Where(t => t.Name.EndsWith("Validator"))
                   .AsImplementedInterfaces()
                   .InstancePerLifetimeScope();


            builder.RegisterAssemblyTypes(assembly);

            builder
            .RegisterType<FluentValidation.Mvc.FluentValidationModelValidatorProvider>()
            .As<ModelValidatorProvider>();

            builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
...

Controller(Works well):

[HttpPost]
public ActionResult Cadastrar(UsuarioCadastrarVM vm)
{
      if(ModelState.IsValid)
      {

      }
}

My ValidatorFactoryBase (Works well):

public class AutofacValidatorFactory : ValidatorFactoryBase
{
    private readonly IComponentContext _context;

    public AutofacValidatorFactory(IComponentContext context)
    {
        _context = context;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        object instance;
        if (_context.TryResolve(validatorType, out instance))
        {
            var validator = instance as IValidator;
            return validator;
        }

        return null;
    }
}

When I send Post with "Nome" and "CargoId" empty in ModelState has only one message "CargoId is required" and not exists that Rule, I think is because CargoId is a integer.

But, Why my Rules are not consider?


Solution

  • The problem was CargoId is a integer, so the MVC is not able to bind my post to my ViewModel, because in my tests I sended a empty value, if I send a value to CargoId or change to nullable (int?) the validation works well.