9

I'm trying to validate a DTO (formModel, whatever term you prefer) which is a bit layered (inheritance and dependencies to other classes).

Is it possible to get the following configuration of models to work:

public abstract class A {

    @NotNull
    private String fieldA1;

    @NotNull
    @Size(min = 2, max = 30)
    private String fieldA2;

    // ... and so on

}


public class B extends A {

    @NotNull
    private String fieldB1;

    @NotNull
    private Xyz fieldB2;

    // and so on
}


public class Xyz {

    @NotNull
    private String fieldXyz1;

    // etc..
}

Spring rest controller:

@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity addCustomer(@RequestBody @Valid B customerDto, BindingResult bindingResult) {
// controller logic here
}

The problem is: only constraint annotations that seem to "work" are those on the parent class A. I submit a request with bad fields in the class A, bindingResult.hasErrors() returns true. If I submit a request with bad fields in classes B or Xyz, bindingResult.hasErrors() is false and the controller just goes on behaving like the request is ok. Any ideas why?

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
Ognjen Mišić
  • 1,219
  • 17
  • 37
  • 1
    If you want to validate object fields, use `@Valid` annotation. http://beanvalidation.org/1.0/spec/#d0e991 – Pavel Horal Jun 18 '18 at 07:59
  • That fixes my object field, but what to do about `fieldB1`? – Ognjen Mišić Jun 18 '18 at 08:06
  • The following link : https://stackoverflow.com/questions/21841202/spring-mvc-validation-of-inherited-classes – 0gam Jun 18 '18 at 09:15
  • Are you sure `fieldB1` validation is not working? That should work... maybe you are setting empty string... in that case, use `@NotBlank` (if you are using Hibernate's bean validation implementation). – Pavel Horal Jun 18 '18 at 16:24
  • yes i'm most positive :) I've already refactored this structure to just have @Valid dependency objects instead of inheritance. Still, would like to know why this is happening – Ognjen Mišić Jun 19 '18 at 07:03
  • add @Validated at controller level. – Deekshith Anand Feb 03 '21 at 04:23

0 Answers0