Extend Spring Bean Validation for the class members

590 Views Asked by At

I have a spring boot application and I am using spring-boot-starter-validation dependency to validate java bean.

My Controller code as below

@PostMapping("/testMessage")
    ResponseEntity<String> testMethod(@Valid @RequestBody InternalMsg internalMsg) {
        return ResponseEntity.ok("Valid Message");
    }

InternalMsg class

public class InternalMsg implements Serializable {
    @NotNull(message = "Msg Num is a required field")
    private String msgNumber;
    @NotNull(message = "Activity Name is a required field")
    private String activityName;
    private MsgDetails msgDetails;
}

The constraints mentioned on InternalMsg are working fine. But constraints specified on MsgDetails class are not working.

MsgDetails class

public class MsgDetails {
    @NotNull(message = "Message Source Name should not be null")
    private String msgSourceName;
    @NotBlank(message = "Message Source ID should not be empty")
    private String msgSourceId;
}

Is there any option to extend validation for the class members of InternalMsg class?

1

There are 1 best solutions below

0
On BEST ANSWER

Add the @Valid annotation to the msgDetails field in the InternalMsg class as well:

public class InternalMsg implements Serializable {
    @NotNull(message = "Msg Num is a required field")
    private String msgNumber;
    @NotNull(message = "Activity Name is a required field")
    private String activityName;

    @Valid // << ----
    private MsgDetails msgDetails;
}