How to validate object programmatically in Spring Boot

  • |
  • 19 May 2023
Post image

Validating objects is crucial to ensure data integrity and prevent errors in subsequent layers of the application. While the @Valid annotation is commonly used for object validation, there are cases where manual validation using the jakarta.validation.Validator provides more flexibility and control.

Let’s assume that you have the following object:

@Getter
@Setter
@HashValidation(groups = FirstOrder.class)
@HistoryValidation(groups = SecondOrder.class)
public class CustomObject {
    @NotBlank
    private String oid;
    @NotBlank
    private String status;
    @NotBlank
    private String total_amount;
    @NotBlank
    private String hash;

    public CustomObject(String oid ...) {
        // ...
    }
}

And after you create the CustomObject with the proper fields, assume that you want to validate it before sending to another layer (another service, or repository). Here is the basic reference code to validate CustomObject:

// ...
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import jakarta.validation.groups.Default;
// ...

@RestController
@Slf4j
@RequiredArgsConstructor
public class AppController {
    private final Validator validator;

    @PostMapping(value = ...)
    public String checkRequest(...) {
        CustomObject customObject = new CustomObject(...);
        Set<ConstraintViolation<CustomObject>> violations = validator.validate(customObject, Default.class, FirstOrder.class, SecondOrder.class, ThirdOrder.class);
        if (!violations.isEmpty()) {
            // there is an error
            throw new ConstraintViolationException(violations);
        }
        log.info("There is no error");
        // ...
    }

}

You May Also Like