Search code examples
javaspringvalidationbean-validationspring-validator

Validation groups extending Default not being validated by default


I have the following validation groups:

public class ValidationGroups {

    public interface Create extends Default {}

    public interface Update extends Default {}

}

And my annotated entity:

public class Usuario implements UserDetails {

    @NotNull(groups = { Update.class })
    @NotBlank(groups = { Update.class })
    @Length(max = 255, groups = { Update.class })
    private String name;

    @NotNull @NotEmpty @Email
    private String email;

}

But when I try to validate my entity using the default validation the field name isn't validated at all, even when it's group explicitly extends Default (annotating with @Valid would do the same):

@PostMapping("signup")
public String createUser(@Validated User user, 
            BindingResult result, Model model, RedirectAttributes redirectAttributes) {

The only way I can get all fields validated is by explicitly adding the Default group in the @Validated annotation like this:

@PostMapping("signup")
public String createUser(@Validated({ Default.class, Update.class }) User user, 
            BindingResult result, Model model, RedirectAttributes redirectAttributes) {

Shouldn't by default all fields annotated with groups extending Default be validated when no groups are specified?


Solution

  • I ran into a similar issue today, so this may help others in the future - the Default relationship works the other way around, as explained here: JSR303 Validation Group inheritance

    When you use @Validated(Update.class), the applied validations are those belonging to Update.class and all of its inheritance chain, so in this case both Update.class and Default.class will apply.

    What you are trying to do is the other way around, i.e. keep @Valid working for all validation groups. In order to do that, you need to redefine the Default group for your class:

    @GroupSequence({Usuario.class, Update.class}) public class Usuario implements UserDetails

    This would allow @Valid to apply all validations.