Spring boot: how to validate 2 optional date parameters are provided as soon as one is provided?

Viewed 346

From a spring boot controller, i'm wondering what is the pattern to follow to verify 2 optional date parameters can't be null as soon as one is provided. in other words, they can be null or both of them filled

public ResponseEntity<CardResponse> getCards(
            @RequestParam(required = false) String orderReference,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime orderPlacementDateStart,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime orderPlacementDateEnd,
            @PageableDefault(page = DEFAULT_PAGE_NUMBER, size = DEFAULT_PAGE_SIZE) Pageable pageRequest) {

}

I saw some class-level constraints but i'm not sure if i can apply it on 2 different params ?

Please tell me what is recommended in this case ?

Thanks

1 Answers

I am answering because I can't comment. I'd recommend combining all these parameters into a POJO and using bean validation to check for validity of request parameters. To validate two fields together, you could try a nested object. See this blog post with examples. This will provide a course-grained approach that is more maintainable and readable.

Related