Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
If you want the validation in a separate object, try FluentValidation. See fluentvalidation.codeplex.com/wikipage?title=mvc. –  rmac Jun 15 '12 at 14:09

3 Answers 3

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();

}
share|improve this answer

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.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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