Will JAX-RS support validation groups?
Asked Answered
J

1

10

From JSR-339:

For simplicity, JAX-RS implementations are NOT REQUIRED to support processing groups other than Default.

This severely limits usefulness of validation in JAX-RS because for example for create and update you are usually using the same model object, but for create the ID of the object should not be provided and for update the ID should be provided, which could be easily validated using validation groups. In general all model objects that are used in more than one flow are impossible to validate.

I do not understand the simplicity argument because Bean Validation already supports groups, so the JAX-RS implementation just needs to pass a group to Bean Validation implementation like Hibernate Validator.

So are there any plans to add validation groups to JAX-RS?

Jamima answered 29/1, 2017 at 18:11 Comment(0)
J
19

It turns out that it does support validation groups. From the same JSR-339:

The presence of @Valid will trigger validation of all the constraint annotations decorating a Java bean class. This validation will take place in the Default processing group unless the @ConvertGroup annotation is present.

For example this is how to validate Account bean in my custom Create or Update groups rather than the Default group:

@POST
@Consumes(MediaType.APPLICATION_JSON)
Response createAccount(@Valid @ConvertGroup(from = Default.class, to = Create.class)
    Account account)

@POST
@Consumes(MediaType.APPLICATION_JSON)
Response updateAccount(@Valid @ConvertGroup(from = Default.class, to = Update.class)
    Account account)

public class Account {

    @Null(groups = Create.class)
    @NotNull(groups = Update.class)
    private String Id;

}

public interface Create {}

public interface Update {}
Jamima answered 15/2, 2017 at 18:54 Comment(5)
Brilliant! I've been looking for this for long time. Though I believe from/to arguments are swapped in the example.Frederiksen
Keep in mind that the validations that will use the @Default group will be not considered anymore, if will use @ConvertGroupContractor
As solution that could not have side effects would be that your new group to extend the Default one. In such way will still work the Default validations.Contractor
Extend as in public class Update extends Default?Padus
from = Default.class is the default and can be omittedRegressive

© 2022 - 2024 — McMap. All rights reserved.