Validate ASP.NET MVC 2 using DTO instead of domain objects

I am trying to bring two best practices together:

  • Using DataAnnotations + ModelBinding for validation in ASP.NET MVC 2
  • Using DTO instead of domain objects when transferring data through ViewModel

If I want to pass DTOs instead of domain entities, then using DataAnnotations + ModelBinding for validation will require me to specify validation attributes on my DTO classes. This leads to a lot of duplication of work, since several DTOs may contain overlapping fields with the same validation restrictions. This means that at any time when I change the validation rule in my domain, I need to find all the DTOs that match this value and update their validation attributes.

+5
source share
3 answers

You should not have more than one DTO for each object, so you will need to apply validation attributes only once per DTO. If you need multiple objects for a view, include multiple DTOs as the properties of your ViewModel.

+2
source

You may find this one useful .

And keep in mind that validation is everywhere. There is nothing wrong with the fact that the DTO uses UI authentication (for example, filling in the necessary fields, date and time in the correct format, etc.) And domain objects - checking the domain (for example, the account has money before the operation is canceled).

You cannot create universal validation. The best you can do is put it in the appropriate places.

, . DTO . , 2 , -, -, .

+2

Perhaps you could use meta annotations that put attributes in a separate class:

namespace MvcApplication1.Models
{
    [MetadataType(typeof(MovieMetaData))]
    public partial class Movie
    {
    }


    public class MovieMetaData
    {
        [Required]
        public object Title { get; set; }

        [Required]
        [StringLength(5)]
        public object Director { get; set; }


        [DisplayName("Date Released")]
        [Required]
        public object DateReleased { get; set; }
    }
}

The sample code was borrowed from this article .

+1
source

All Articles