1

I am trying to validate a model, which is inheriting from another model and this parent model has @NotBlank annotation to validate a parameter. But this validation is bypassed in the controller which is accepting a list of child class objects.

The code snippet should give a fair idea of the scenario

public abstract class A {
  @NotBlank
  private String name;
}

public class B extends A {
  private String type;
}

@PostMapping(consumes= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity saveRoles(@Valid @RequestBody List<B> roles){
   // ideally it should not land here if request has blank name. But it seems to land here.
   // logic 
}

The request body -

[
    {
        "name": "",
        "type": "system"
    }
]

Chiku
  • 11
  • 2
  • 1
    Yes it should and the issue is not related to the annotation not being processed but to how `javax.validation` works. You will need to put `@Valid` on the `` on the list as well. So `List<@Valid B>`. As you are accepting a collection it needs to know it should propagate the validation. – M. Deinum Sep 16 '20 at 06:23

1 Answers1

0

You trying to validate the collection itself, but not the collection elements. Try this:

@PostMapping(consumes= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity saveRoles(@RequestBody List<@Valid B> roles){
  
}
donquih0te
  • 597
  • 3
  • 22
  • Hi @donquih0te Is this dependent on spring-boot version? I got this working for 2.2.4 but it did not work for my existing version 2.0.3 – Chiku Sep 24 '20 at 08:44
  • @Chiku Could you go to the `@Valid` annotation source code and check if `ElementType.TYPE_USE` is present inside the `@Target` – donquih0te Sep 24 '20 at 10:04
  • Yes it is present. Since I had time constraints, I got it working by building a wrapper java bean for the list. I referred this link - [link](https://stackoverflow.com/questions/23012841/receiving-json-and-deserializing-as-list-of-object-at-spring-mvc-controller/39079259) – Chiku Sep 25 '20 at 05:38