In my Springboot project I need to perform a validation of the type validFromDate<validToDate. I was wondering whether would it be a good or bad practice to place a validation in the model itself (pros and cons?) or should it be in the controller which feeds the value in model. I have taken reference from this question In MVC should a model handle validation?.

In it the accepted answers favors for the case of date validation in model, but there are answers which contradict as well. So I would like to have clearer view on the topic.

Which clearly provides some insights, but I was looking for this particular scenario. (As a concrete example for the above question).

Thanks very much for any insights!

有帮助吗?

解决方案

The controller should always handle validation. Because its the only one capable of actually presenting the problem to the user (be that a message, some sort of highlight, etc..).

That being said, always enforce invariants in the core model. I'm not talking about business rules, those should be enforced by business logic. I'm talking about structural rules. These are the invariants like an empty container has no elements.

In your case I cannot see how this rule could be structural. A close by example that is structural would be a DateRange with the invariant DateRange.From <= DateRange.Till because otherwise the from and till swap.

许可以下: CC-BY-SA归因
scroll top