I like the extnesibility point of MVC, allowing view models to implement IValidatableObject, and add custom validation.

I try to keep my Controllers lean, having this code be the only validation logic:

if (!ModelState.IsValid)
    return View(loginViewModel);

For example a login view model implements IValidatableObject, gets ILoginValidator object via constructor injection:

public interface ILoginValidator
    bool UserExists(string email);
    bool IsLoginValid(string userName, string password);

It seems that Ninject, injecting instances in view models isn't really a common practice, may be even an anti-pattern?

Is this a good approach? Is there a better one?

  • If you want the validation in a separate object, try FluentValidation. See fluentvalidation.codeplex.com/wikipage?title=mvc.
    – rmac
    Jun 15, 2012 at 14:09
  • +1 Great idea to inject a separate Validator class, that solves my problem where I have to access database information for validation!
    – magnattic
    Apr 27, 2015 at 15:04

3 Answers 3


Personally, to me your design seems clean.

IValidatableObject means the view model will provide some validation that can't be provided by simple attributes - injecting the real validator which will call services / databases / whatever keeps your design clean and ensures you don't violate the single responsibility principle - View Models are responsible, essentially, for transferring data and validating the data that is transferred (whether it be through attributes or IValidatableObject or both).


Having a dedicated object for validation guarantees that you respect SRP indeed - which was already the case anyway since it's a typical responsibility of a view model to validate its data.

As for injecting instances into view models, I can't see anything wrong with that. There's virtually no limit to what can be injected into what.


Instead of injecting the ILoginValidator into your VM constructor you can use the ValidationContext (which is the arg to IValidatableObject.Validate()) to get your Validator.

public IEnumerable<ValidationResult> Validate(ValidationContext vc)

var loginValidator = (ILoginValidator)vc.GetService(typeof(ILoginValidator));
return loginValidator.Validate();


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.