0

Example:

public class UserValidator : AbstractValidator<UserViewModel>
{
    public UserValidator()
    {
        RuleFor(p => p.Username).NotEmpty()
            .WithMessage("Please enter a username.");
    }
}

public class UserController : ApiController
{
    public IHttpActionResult Create(UserViewModel vewModel)
    {
        if (ModelState.IsValid)
        {
            return Ok();
        }

        return BadRequest();
    }
}

Just by providing the UserController.Create() method and UserViewModel object, how can you get the UserValidator object or type?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Dennis Laping
  • 682
  • 1
  • 7
  • 18
  • you should just need to add FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration); to your Global.asax file – cecilphillip Jun 09 '15 at 18:44

1 Answers1

0

You can do two things:

Either inject your validator into the constructor of your controller, like so:

public class UserController : ApiController
{
    private readonly IValidator<UserViewModel> userViewModelValidator;

    public UserController(IValidator<UserViewModel> userViewModelValidator)
    {
        this.userViewModelValidator = userViewModelValidator;
    }
}

And then in your method, call:

var validationResults = this.userViewModelValidator.Validate(vewModel);

You can also just new one up:

public IHttpActionResult Create(UserViewModel vewModel)
{
    var validator = new UserValidator();

    if (validator.validate(vewModel).IsValid)
    {
        return Ok();
    }

    return BadRequest();
}

Alternatively, there is some attribute based validation you can do, which probably aligns more with what you want.

public class UserViewModel
{
    [Validator(typeof(UserValidator))]
    public string UserName { get; set; }
}

You will have to wire it up in your composition root, which for Web.Api projects is your global.asax file, in your Application_Start() method.

protected void Application_Start()
{
    // ..other stuff in here, leave as is
    // configure FluentValidation model validator provider
    FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration);
}
Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34