Issue
I have a simple class, which I'd like to validate:
public class Model {
@NotNull
private String someField;
@AssertTrue
public boolean methodConstraint() { ... }
}
This class is validated as part of the inputs of a spring controller method.
I managed to configure the validation of the fields (someField
in this case), but for some reason the methodConstraint()
isn't even invoked, let alone validated. I remember this being possible.
I use the default Spring boot 2.6.6 configuration for validation, which means I use the 6.2.3 version of hibernate validator, with the 2.0.2 API version.
I suspect it is the ValidatorImpl:454
where thing go sideways, because this method only validates (direct) meta constraints, but method constraints don't seem to be considered as such.
Solution
Assuming you have something like
@Controller
class ModelController {
...
public Result mappedMethod(@Valid Model model) {
...
}
}
then the model will be validated as a JavaBean. Meaning only fields and getters will be considered.
If a model class is modified to:
public class Model {
@NotNull
private String someField;
@AssertTrue
public boolean isMethodConstraint() { ... }
}
where the constrained method starts following the JavaBean requirements (method name begins with is/get
and has 0 parameters) then that method will be executed during the validation.
Alternatively, if beans do not follow the JavaBean format then a custom strategy can be used. See the documentation here. But if possible - it'll be easier just to update the model classes and make constrained methods start with is/get
.
Answered By - mark_o
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.