I'm implementing a Rest API where I have to do some validation on the request body. Based on a value defined in a field called "type" in my Json, I want to set groups to Spring Validator dynamically.
By looking to the documentation the only solution I found is to set @Validated annotation at method signature and hard coding the groups to pass to it.
I found an alternative solution using Validator from javax.validation package, and my code looks like this for now:
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<EnterpriseResource>> constraintViolationSet = new HashSet<>();
if (isTypeEnterprise(enterpriseResource, EnterpriseTypeEnum.BUYER)) {
constraintViolationSet = validator.validate(enterpriseResource, BuyerEnterprise.class);
}
if (isTypeEnterprise(enterpriseResource, EnterpriseTypeEnum.PROVIDER)) {
constraintViolationSet = validator.validate(enterpriseResource, ProviderEnterprise.class);
}
if (!constraintViolationSet.isEmpty()) {
log.info("=========================ERRORS: {}", constraintViolationSet.toString());
throw new ConstraintViolationException(constraintViolationSet);
}
Is there any workaround so that I can get the same behavior using Spring native Validator instance?
Here is a helper class that makes use of spring MVC validator and allows you programmatically to specify validation groups.
@Component
public class ValidatorTool {
private static final Method method = ValidatorTool.class.getMethods()[0];
@Autowired
@Qualifier("mvcValidator")
private org.springframework.validation.Validator validator;
@SneakyThrows
public void validate(Object object, Object... validationGroups) {
DataBinder binder = new DataBinder(object);
binder.addValidators(validator);
binder.validate(validationGroups);
BindingResult br = binder.getBindingResult();
if (br.hasErrors()) {
log.info("Validation of {} failed: {}", object.getClass(), br.getAllErrors());
throw new MethodArgumentNotValidException(
new MethodParameter(method, 0),
br);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With