Suppose I have a web application that processes a request as follows.
- A user fills in a form and submits it. (e.g., to register as a new user for my application)
- The request is passed to the appropriate view/controller in the backend of my application. (e.g., a request
CREATE /useris passed on to a
- This controller passes on the request to a repository in the data layer (e.g., to a
UserRepository, which is responsible for storing new users by communicating with a database)
- This repository accesses the database and performs the necessary queries (e.g., add a new row to a
usertable containing the user's data)
At which point(s) should I validate the request?
To take the simple example of registering a new user, I should make sure that its mail address is in the correct format. I know that I should definitely validate this in the frontend for fast feedback, and that I should definitely validate this in the backend too because the frontend cannot be trusted. However, at which point in the backend should this be done?
- Validating the mail address inside the
UserRepositorywill make sure that other application logic will not accidentally insert invalid users into the database.
- I think implementing validation rules such as validating mail addresses inside the database itself might be infeasible (both practically and efficiency-wise)
- I typically see that validation is only done in views/controllers to validate incoming requests. For example, I'm currently using the Nest.js framework, which uses a concept called validation pipes to validate data right before they reach the implementation of a controller. They don't mention anything about validation after that.
- Validating both inside
UserRepositorywill check the same things twice, which seems unnecessary.