Search code examples
asp.net-coredomain-driven-designcqrsclean-architecture

How to validate input data if there are CQRS, DTO and Entity?


.Net Core 3, Clean Architecture.

I have read a lot articles about data validation with CQRS. For example there and there.

I have done some conclusions:

  1. Need to validate data in DTO. It is contract for entities.
  2. Some suggestions from authors validate date into entities (domain).
  3. In CQRS AbstractValidator we can validate too, but other rules.

Email field validation will be in 1 and 2. Age restriction will be in 3.

But three validations in server + one in client are problem (big DRY). Where is better validation in DTO or Entities? I think in DTO, because when I get DTO from input, I can validate and call ModelState.IsValid. But I read some articles that need validate input data in entities too.

So, I'm confused. Can you explain me:

If need to validate an Email field, and an age restriction (18), where need to put validation in Clean Architecture with CQRS?


Solution

  • All your Api contracts, commands should rely on primitive types. Once you want to initialize your domain model, here is where you will not be able to do it, if smth is wrong. If you do DDD, it suggests to prevent object being in invalid state versus validating an invalid object (Domain model vs Crud based).