1

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?

LearnToCode
  • 169
  • 1
  • 5
  • 19

1 Answers1

1

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;
}
Michiel
  • 2,914
  • 1
  • 18
  • 27