1

In building an app, we created a generic object model to store some values, the viewmodel looks a bit like this at the moment:

public class FooViewModel {
    public int ID { get; set; }

    public byte FooType { get; set; }

    [Required]
    [Display(Name = "Bar Name")]
    public string Name { get; set; }

    [Required]
    public string Email { get; set; }

    //etc, etc
}

The problem is: depending on the FooType, we want to have the Display Name to be different and the Email is not required for type 1 and 2, but is required for type 3 and 4.

We tried seperating out the properties that differ per type in to classes that inherit from this one, but the validation does a fallback on what is specified in the base type, so that didn't work.

Currently, the only option seems to be to create a viewmodel for each FooType (and also seperate controllers and view), which leads to a lot of code duplication.

What are other ways to keep this DRY?

Community
  • 1
  • 1
sebastiaan
  • 5,870
  • 5
  • 38
  • 68

2 Answers2

1

To benefit a validation context (e.g. validating objects in different contexts), I strongly recommend using FluentValidation library.

Hadi Eskandari
  • 25,575
  • 8
  • 51
  • 65
  • 1
    I'm afraid this might indeed be the way to go. It's not quite as sexy and convenient as the default validation framework, but all signs are starting to point to this library. – sebastiaan Jan 24 '12 at 22:35
  • +1 for the FluentValidation recommendation. I actually find it a bit "sexier" than Microsoft's data annotation solution, because it allows you to separate the concerns of view presentation from validation (allowing you to validate the same view model in different contexts). – Brandon Linton Feb 08 '12 at 02:54
0

You could implement a custom RequiredIf validation attribute, or you could implement IValidatableObject.

Community
  • 1
  • 1
jrummell
  • 42,637
  • 17
  • 112
  • 171
  • I understand IValidateObject doesn't come with the unobtrusive validations, so you only get to validate on the server, no? – sebastiaan Jan 24 '12 at 22:34
  • I believe you are correct. FluentValidation might be a better option. I haven't used it yet, but I've heard very good things about it. – jrummell Jan 25 '12 at 13:18
  • This answer addresses the lack of client validation with IValidatableObject http://stackoverflow.com/questions/4748703/ivalidatableobject-in-mvc3-client-side-validation. – jrummell Jan 25 '12 at 13:21