Search code examples
spring-bootspring-restspring-validation

Spring boot rest requestbody and @valid not working when object is null/empty


I am trying to apply not null validation on an attribute of my request which is instructedAmount but it is not working. I have a Spring Boot (V2.3.0.RELEASE) application with the following endpoints:

@Validated
public class TestController {
@PostMapping(value = "/test/pay")
    public ResponseEntity<IPSPaymentResponse> validatePayt(@Valid @RequestBody InstantPaymentRequest instantPaymentRequest) {
        log.debug("start validatePayment method {}", instantPaymentRequest);
....

The InstantPaymentRequest is as follows:

@Data
@Validated
public class InstantPaymentRequest {
    @Valid
    private PaymentIdentificationRequest paymentIdentification;
    @NotBlank(message = "transactionTypeCode.required")
    private String transactionTypeCode;
    @Valid
    private InstructedAmount instructedAmount;
    @Valid
    private CustomerRequest debtor;

The instructed amount is as follows:

    @Data
public class InstructedAmount {

    @NotBlank(message = "currency.required")
    private String currency;
    @NotBlank(message = "value.required")
    private String value;
}

Basically when the instructedAmount is provided in the payload but for example I miss currency attribute in payload, the validation is working fine, the non null error message is displayed correctly and my rest controller endpoint is not called.

However when instructedAmount is not provided in the payload, no mandatory error message is displayed and my rest endpoint is called, it this the correct way or I am missing something?

I thought since attribute of InstructedAmount cannot be null then InstructedAmount also cannot be null/empty.

How to add InstructedAmount not null validation in the above scenario with annotation?


Solution

  • Use @NotNull together with @Valid:

    @NotNull
    @Valid
    private InstructedAmount instructedAmount;
    

    From https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-object-graph-validation:

    Note that null values are getting ignored during cascaded validation.