Jean Carlos Jean Carlos - 1 month ago 4x
C# Question

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):


var assembly = Assembly.GetExecutingAssembly();

.Where(t => t.Name.EndsWith("Validator"))




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

Controller(Works well):

public ActionResult Cadastrar(UsuarioCadastrarVM vm)


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?


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.