Joseph Downing
Joseph Downing

Reputation: 1119

Validating fields of a type before applying a custom constraint validator to it

I have a class that is something like this

@MyValidator
class Demo {
    @NotNull
    Instant startDate
    ...
}

In the ConstraintValidator for the MyValidator constraint, I make a call that requires startDate not to be null.

I wouldn't have to worry about that if the @NotNull constraint on startDate is validated before my @MyValidator constraint is, but in my tests @MyValidator is validated first and I am getting an NPE.

How can I either indicate to the validator that calls my ConstraintValidator that the @MyValidator constraint should be validated after the field level @NotNull constraint is, or explicitly validate the @NotNull constraint myself as the first step in my ConstraintValidator implementation?

Upvotes: 4

Views: 2282

Answers (1)

skyrosbit
skyrosbit

Reputation: 66

You can control validation order by using validation groups and group sequences. Info: Group sequence stops validation if one of the groups, defined in a group sequence, fails.

http://beanvalidation.org/1.1/spec/#constraintdeclarationvalidationprocess-groupsequence

If you are using Hibernate Validator, this link may help too: https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-groups.html

Upvotes: 5

Related Questions