Data validation
Hello, I have a question regarding data validation. I'm working on a project in ASP.NET Core WebApi. My project consists of 3 layers: Core, Infrastructure, and WebApi. I'm using the Repository pattern. I'm wondering in which layer to perform data validation. Let's take the example of user account registration. Data such as email, password (with password validation handled in the PasswordService), first name, last name, etc., are passed to the API. Should I validate this data in the Core layer when creating the Customer object (e.g., in the constructor using methods like SetName, SetEmail, etc.), or should I create a class responsible for data validation in the WebApi layer? Thank you in advance for your help
6 Replies
The short answer is "it depends".
The long answer is very long, so I'll give you the medium length one instead
There are multiple types of validation. The very first one we have is model binding, and it mostly cares about the very basics, like that the user passed a valid number to your
int
parameter
Model binding is done by ASP.NET for you automatically, but can be customized if needed.
Next up is "input validation". This is stuff that can easily be checked on a given model without any external dependencies, like checking if a string is of a certain length, or that a number is within a given span, or a datetime is in the past/future etc.
Input validation can be placed in a few places, you could do it in the controller (webapi layer), or as part of constructing your command object, or in the handler (or service method).
After that, we have "business validation". The input was of the right type, and of the right length, and had the required characters... but what if the email is already taken, or that seat is already booked, etc.
No easy way out here, we can't say if an email is available or a seat is booked without checking the database. This is part of your application business logic, and not strictly related to validating the model itself - the model is valid, but given your current state, some of the content of the model violates other rules.
Business validation should always be part of your handler/service method, since its part of the business logic itself@ZML Before you start, I do not recommend using multi layer architecture. Honestly it just makes things more complicated. You should take a look at
vertical slice architecture
. Also if you are using Ef Core
, than Repository Pattern
makes no sense. It's already kind of inbuilt.
I would recommend, combining MediatR
with FluentValidation
.$vsa
$norepopattern
Derek Comartin
CodeOpinion
Have you replaced your DB because of the Repository Pattern?
Have you been able to replace your database implementation transparently because of the use of the repository pattern?