springboot validator manually validate
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class YourObjectValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return YourObject.class.isAssignableFrom(clazz);
}
@Override
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:
- Import necessary Spring framework classes for validation.
- Implement the
Validator
interface. - Override the
supports
method to check if the validator supports the given class. - Override the
validate
method to perform custom validation logic. - Cast the target object to the type you want to validate.
- Use
ValidationUtils.rejectIfEmptyOrWhitespace
to check if specific fields are empty or contain only whitespace. - Use
errors.rejectValue
for custom field-level validations with specified error codes and messages. - Perform additional custom validations based on business logic.
- Use
errors.reject
for general errors with a specified error code and message.