Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SmartValidator - manually calling validate with groups

Spring 4.3.2

I need to call SmartValidator.validate() manually and I need it utilize the validation groups that I have defined on the target entity. The javadoc says this...

"This variant of validate() supports validation hints, such as validation groups against a JSR-303 provider (in which case, the provided hint objects need to be annotation arguments of type Class)."

void validate(Object target,
          Errors errors,
          Object... validationHints)

For some reason, I cannot find much information or examples on using "validationHints". So I have been trying things like the following...

validator.validate(targetEntity, errors, new Class[]{ValidationGroup1.class});

validator.validate(targetEntity, errors, ValidationGroup1.class);

So far, it just completely ignores my groupings. It always calls all validators. Any ideas?

Thanks!

===================================

Update: The javadoc also says this..

"Note: Validation hints may get ignored by the actual target Validator, in which case this method should behave just like its regular Validator.validate(Object, Errors) sibling."

This sounds like what's happening. But it doesn't give any clue as to why it might ignore it.

like image 221
Jim Ott Avatar asked Aug 29 '16 15:08

Jim Ott


People also ask

How do you validate query parameters in spring boot?

Validating a PathVariable Just as with @RequestParam, we can use any annotation from the javax. validation. constraints package to validate a @PathVariable. The default message can be easily overwritten by setting the message parameter in the @Size annotation.

Is @valid and @validated the same?

The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.


1 Answers

Alright then. It seems the 'answer' is to not use Spring for this. Here is my workaround...

import javax.validation.Validator;
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation> violations = validator.validate(targetEntity, new Class[]{group1.class, group2.class});

Then I convert Set to Spring FieldErrors (since everything is already configured to run Spring). Kind of a clusterf***, but at least it's working now.

like image 168
Jim Ott Avatar answered Sep 24 '22 16:09

Jim Ott