djmj
djmj

Reputation: 5544

bean validation get validation groups

Is it possible to get the groups within the validator the validation method is invoked with?

I have multiple groups (Create, Update, Delete) which most result in similar validation for the one bean.
Instead of providing multiple almost identical validators (and create utility functions to externalize same validation code) I would prefer to have a single Validator which handles the validation regarding the groups the validation was invoked with.

In worst case I have 3 times n single Validators and n utility classes for shared code instead of just n validators.

Validator.validate(Object, Class<?> ... groups)

How do I get those groups within my Validator to do something pseudo-like?

if (groups.contains(Create.class)) // validate create stuff

Upvotes: 2

Views: 1578

Answers (2)

djmj
djmj

Reputation: 5544

As @hardy stated in his answer its not possible to retrieve the validation groups at runtime within the validator implementation. But it can be done using a workaround creating a different annotation and specifying the group or using repeating annotations.

Example:

Bean

@ValidFoo
@ValidFoo(bar = true, groups =
{
    FooBarGroup.class
})
public class Foo 
{
    private Bar bar;
}

Annotation

@Repeatable(ValidFoo.List.class)
public @interface ValidFoo
{
    public String message() default "{package.ValidFoo.message}";

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

    Class<? extends Payload>[] payload() default {};
    
    /*
     * toggle bar validation
     */
    public boolean bar() default false;

    public @interface List
    {
        ValidOrderCost[] value();
    }
}

Implementation

public class FooValidator implements ConstraintValidator<ValidFoo, Foo>
{
    private boolean bar;

    @Override
    public void initialize(final ValidFooconstraintAnnotation)
    {
        this.bar = constraintAnnotation.bar();
    }

    
    @Override
    public boolean isValid(final Foo foo, final ConstraintValidatorContext context)
    {
        // 1. default validations
        
        // 2. toggle bar specific validation
        if (this.bar)
        {
            // validate bar
        }

        return true;
    }
}

Upvotes: 0

Hardy
Hardy

Reputation: 19119

In case you are asking how to determine the currently validated constraints within a custom constrain (ConstraintValidator implementation), the answer is you cannot.

The concepts of groups and constraint are orthogonal. A constraint should not behave differently depending on the group which gets validated.

In this context, think about users of constraints. How would they know what their constraint does if the validation is conditional?

Upvotes: 1

Related Questions