I am trying to implement DDD along with Hexagonal Architecture. One of the things that I am struggling with is validations. I had explored a lot of articles on where the validation should be but it seems there is no one way. I would like to find the most appropriate way to implement in my scenario. Here is the scenario.
- I have an HTML page which contains few fields like Title, Date, Assignee.
- This HTML page has basic validation for empty fields. Once the form is submitted it calls one of the rest services.
- The job of Rest Controller is just to send the data sent from the browser to one of the services.
- So the method in the service class will accept that input. I'm not trusting in the caller. I want to validate the input before creating any domain object.
Here an example of the validations I need to do
- The title should not be empty
- Title length should be less than X characters (The value of X is configurable and retrieved from the database)
- The assignment should be from a predefined set of available assignments(Retrieved from another application or DB)
The solution implemented (at the moment) starts with an interface
public interface IValidator<T> {
public ValidationResult validate(T entity)
}
Then, I have implemented multiple validators. For instance, TitleValidator, DateValidator and AssignmentValidator.
Since the number of implementations might increase, I have created a wrapper to hold and configure the validators. Finally, the wrapper is injected into the services.
public class MyService {
public MyService(WrapperValidator wrapperValidator){
}
public void createData(InputData inputData){
ValidationResult result = this.wrapperValidator.validate(inputData);
if(result.Ok()){
//Proceed with domain objects creation and applying business rules. Domain objects will have other validation as well.
}
}
}
I retrieve the configuration parameters like max length, predefined set of assignees and sending these settings to the validators from the wrapper.
The WrapperValidator
is accessing database and external API to retrieve these configurations.
Is this the right way or should every validator retrieve its configuration by itself?
Any suggestions, improvements or guidance from more experienced developers is appreciated.