0

I am trying to create a validator that is given the following method signature:

public void validateAllParameters(
    final Method method,
    final Object[] parameterValues)

If there is a violation, I would be throwing a ConstraintViolationException

I can iterate through parameterValues and run .validate() on each, but when I do that I do not have the path information that includes which parameter.

I tried to assemble parameterValues into a map like this

Map<String, @Valid Object> parameterMap = new LinkedHashMap<>();
for (int i = 0; i < method.getParameterCount(); ++i) {
    parameterMap.put(method.getParameters()[i].getName(), parameterValues[i]);
}

But

Set<ConstraintViolation<Object>> errors = validator.validate(parameterMap);

is an empty set i.e the validation didn't execute on the map.

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

2 Answers2

0

if you use springframework, you can use MethodValidationPostProcessor implements method level validate like this.

@Validated
@Service
public class GreetingService {

public GreetingService() {
    System.out.println("init GreetingService");
}

public void validate(
        @Min(message = "service中的page不能小于5", value = 5) int page,
        @Max(message = "service中的size不能大于20", value = 20) int size) {
    System.out.println(page + " : " + size);
}
}

you can catch the ConstraintViolationException to get the validate errors, and MethodValidationPostProcessor config.

public Map handle(ConstraintViolationException exception) {
    return error(exception.getConstraintViolations()
            .stream()
            .map(ConstraintViolation::getMessage)
            .collect(Collectors.toList()));
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
}

Hope to help you

Tonney Bing
  • 230
  • 2
  • 9
0

Why not use BeanValidation parameter validation? (link to doc). If for example we have a class:

class Foo {
  public void bar(@NotNull String string) {
  }
}

And you want to validate parameters for bar method you could do it like:

ExecutableValidator executableValidator = Validation.byDefaultProvider().configure()
  .buildValidatorFactory().getValidator().forExecutables();

Foo foo = new Foo();
  Object[] parameterValues = { null };
  Method method = Foo.class.getMethod( "bar", String.class );
  Set<ConstraintViolation<Foo>> violations = executableValidator
  .validateParameters( foo, method, parameterValues );

assertThat( violations ).hasSize( 1 );
mark_o
  • 2,052
  • 1
  • 12
  • 18