springboot validator manually validate

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class YourObjectValidator implements Validator {

    public boolean supports(Class<?> clazz) {
        return YourObject.class.isAssignableFrom(clazz);

    public void validate(Object target, Errors errors) {
        YourObject yourObject = (YourObject) target;

        // Validate fields using ValidationUtils.rejectIfEmptyOrWhitespace
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fieldName1", "error.code.required", "Field 1 is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fieldName2", "error.code.required", "Field 2 is required.");

        // Custom validations based on business logic
        if (yourObject.getSomeCondition()) {
            errors.rejectValue("fieldName3", "error.code.invalid", "Field 3 is invalid.");

        // Perform more custom validations as needed
        if (yourObject.getSomeOtherCondition()) {
            errors.reject("error.code.general", "General error message.");

In the provided example:

  1. Import necessary Spring framework classes for validation.
  2. Implement the Validator interface.
  3. Override the supports method to check if the validator supports the given class.
  4. Override the validate method to perform custom validation logic.
  5. Cast the target object to the type you want to validate.
  6. Use ValidationUtils.rejectIfEmptyOrWhitespace to check if specific fields are empty or contain only whitespace.
  7. Use errors.rejectValue for custom field-level validations with specified error codes and messages.
  8. Perform additional custom validations based on business logic.
  9. Use errors.reject for general errors with a specified error code and message.