Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
sunny-java-dev Avatar asked Jul 16 '26 23:07

sunny-java-dev


2 Answers

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.

like image 153
JuWon Lee Avatar answered Jul 19 '26 13:07

JuWon Lee


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.

}
like image 42
Slevin Avatar answered Jul 19 '26 13:07

Slevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!