0

I know this question has been asked before but unfortunately I can't get the answers to work (How to validate field level constraint before class level constraint?).

I have the following Pojo:

@ValidBalanceData(allowableBalanceDifference = 0.01)
public class Mutation {

    @NotNull() private BigDecimal balanceBefore;

    @NotNull() private BigDecimal balanceAfter;

    @NotNull() private BigDecimal amount;

    ....
}

I have implemented the ValidBalanceData annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BalanceDataConstraintChecker.class)
public @interface ValidBalanceData {
    String message() default "{nl.smith.balanceData.message}";

    double allowableBalanceDifference();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

I also implemented the validatedBy class. Unfortunately the ValidBalanceData constraint is validated before the NotNull constraints. Since the ValidBalanceData constraint assumes the balanceBefore, balanceAfter and amount values not to be null this results in a Nullpointer Exception. How do I solve this problem? Can somebody give me a working example (using @GroupSequence and fields)?

2
  • [this could be the voice of my ignorance] - what about making the ValidBalanceData annotation field-targeted, and then apply it to a field in conjunction with @Valid (instead of applying it to the actual bean class)? Commented Sep 12, 2018 at 17:03
  • What is your logic of validation? Commented Sep 12, 2018 at 18:57

1 Answer 1

2

I found the answer:

@GroupSequence({ FieldChecks.class, Mutation.class })
@ValidBalanceData(allowableBalanceDifference = 0.01, groups =  Default.class)
public class Mutation {

private Integer id;

@NotNull(groups = FieldChecks.class)
private BigDecimal balanceBefore;

@NotNull(groups = FieldChecks.class)
private BigDecimal balanceAfter;

@NotNull(groups = FieldChecks.class)
private BigDecimal amount;

....

}

FieldChecks is a userdefined empty marker interface and javax.validation.groups.Default comes from the validation jar.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.