william-r
11/14/2017 - 4:00 PM

FluentValidation as service .Net Core 2

FluentValidation as service .Net Core 2 using dependency injection

private IValidator<MyModel> _pv;
//ctor
public ModelController(IValidator<MyModel> pv)
{
    _pv = pv;
}

[HttpPost("add")]
public bool Post([FromBody] MyModel model)
{
    var x = _pv.Validate(model, ruleSet: "common").IsValid;
    return x;
}
RuleSet("common", () =>
{
    RuleFor(x => x.Id)
        .NotEmpty()
        .NotNull()
        .WithMessage("ID must not be empty, please add an ID property");
});
  
  
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public bool Active { get; set; }
services.AddMvc()
  .AddFluentValidation(fvc => 
    fvc.RegisterValidatorsFromAssemblyContaining<MyModelValidator>())
      .AddJsonOptions(o => o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

services.AddTransient<IValidator<MyModel>, MyModelValidator>();