views:

17

answers:

1

I am working on a project which requires different validation sets for the same model, and we're trying to find the best solution to handle it.

A simplified example could be using our Customer DTO:

public class Customer
{
    [Required]
    public string FirstName { get; set; }

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

    [Required] // Only required on some views
    public string Title { get; set; }
}

In our first view, all fields are required, as they're shown in the DTO using DataAnnotations.

In our second view, FirstName and LastName may be required, but Title is optional, and may not even be represented on the view.

The complication comes in, that we want to have validation rules live in our service layer (so that we can provide an API at a later point utilizing the same validation), which can access the data annotations, and validate against them, reporting back up to the UI if they don't validate.

So far, the winning method is:

  • Every view has a dedicated viewmodel, which the DataAnnotations exist on.
  • The viewmodel then maps our domain objects using something like Automapper.
  • The domain objects are then passed to the repositories and services to have actions taken upon them.

This also means:

  • Validation would not occur in the service layer, since by the time the objects got there, they would be domain objects instead of viewmodels.

Is there some better way that we should be handling this for an enterprise application? We have yet to find a solution.

A: 

You can't cram all your validation into one place when it's context-specific. Use your winning method, but also have your entity services do appropriate validation in that layer.

Craig Stuntz