1

I have a POST API written in Spring Boot. I need to validate some data conditionally. For example, this is my JSON:

{
  "p1": false,
  "p2": true,
  "p3": false
}

The validation I am trying to achieve here is

  • If p1 is false, then p3 should also be false.

  • If p1 is true, p3 doesn't need to be true.

Is there some example of conditional JSON validation in Spring to refer from?

1 Answer 1

1

You can write a custom constraint for your object.

The rest end point.

@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public ResponseEntity<String> doSomething(@RequestBody @Valid MyObject myObject) {

The body POJO.

@MyConstraint(message = "p1 is false, p3 should also be false")
public class MyObject {

    private boolean p1;
    private boolean p2;
    private boolean p3;

   //getters and setters
}

The constraint annotation being used by MyObject

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {

    String message() default "Invalid object";

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

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

The Validator that the constraint kicks off.

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, MyObject> {

    @Override
    public boolean isValid(MyObject value, ConstraintValidatorContext context) {

        if (!value.isP1()) {
            return value.isP1() == value.isP3();
        }

        return true;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

What are the fully qualified names of the ConstraintValidator and ConstraintValidatorContext classes?

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.