spring-bootjakarta-validation

What does jakarta.validation.Valid validate?


@Valid annotation is commonly used within the Bean Validation API scope. It’s primarily employed to enable form validation or validation of model objects.

//Below are my pojo classes

public class User {

 private UserDetails userDetails;
 private List<UserSubscribtion> subscribtions; 

}

public class UserDetails {

 private String userId;

}

public class UserSubscribtion{

 private boolean isSubscribed;
 private String subscribtionType;

}

I have a controller methods that has the @Valid annotation.

@PostMapping(value = "/saveUser", consumes ={MediaType.APPLICATION_JSON_VALUE},produces{MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<Object> saveUser(@RequestBody @Valid User user){

// Controller code.

}

What kind of validations does @Valid do here? How can I verify it in a test?


Solution

  • When you use @Valid on an object, it tells the Spring framework to apply validation rules defined by annotations within the object's class and its field classes before proceeding with the method's execution. The actual validations are defined by constraints in the form of annotations. Like @NotNull, @Min, @Max, etc placed on the fields of the class.

    public class User {
         @NotNull
         private UserDetails userDetails;
         
         @NotEmpty
         private List<UserSubscription> subscriptions;
    }
    

    To verify validation in a test, you can use Spring's MockMvc.