What does jakarta.validation.Valid validate?

346 Views Asked by At

@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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

You not only have to apply @Valid to perform a validation against the validation annotations you've put on the fields, you also have to check whether the validation was successful and take further actions in case of.

To do this, you add BindingResult directly after the instance you wanna validate:

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

    if (bindingResult.hasErrors())
        { /* do whatever you wanna do */ }

    // Controller code.

}