Custom validation in elements of a list of a rest request

99 Views Asked by At

I have a spring rest service that receives a list of elements, like this:

@RequestMapping(value = "/foobar", method = RequestMethod.PUT)
public ... foobar(
        @Valid @RequestBody(required = true) List<Exp> listDto) {

I created an annotation @MyConstraint,

@Constraint(validatedBy = MyValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyConstraint{

    String message() default "differents in list";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

and

public class MyValidator
    implements ConstraintValidator<MyConstraint, List<Exp>> {

@Override
public boolean isValid(List<Exp> values, ConstraintValidatorContext context) {

    return values.stream() //
                    .map(Exp::getExpedientes) //
                    .map(G::getIdArea) //
                    .distinct() //
                    .count() != 1;// more than one

    }

@Override
public void initialize(MyConstraint constraintAnnotation) {
    ConstraintValidator.super.initialize(constraintAnnotation);
    }

}

@MyConstraint
public class Exp {
    private List<G> expedientes;
}   

public class G  {
    private Integer idArea;
}

but when I make a request to my web service, the validation is not being executed, even setting a return false;, the request is received, am I missing something to indicate the execution of the validation?

1

There are 1 best solutions below

5
On

Just annotating @Valid on the method argument is not enough . You also have to annotate @Validated at the controller class level in order to enable the method validation. Do you miss it ? Something like the following :

@RestController
@Validated
public class FooController {
  
  @RequestMapping(value = "/foobar", method = RequestMethod.PUT)
  public ... foobar(@Valid @RequestBody(required = true) List<Exp> listDto) {


  }
}


It is mentioned at here :

To be eligible for Spring-driven method validation, all target classes need to be annotated with Spring’s @Validated annotation, which can optionally also declare the validation groups to use.