0

Is there a way to let a validator specify the message when the validation fails? I know I can implement the annotation so I can use it like this (would probably use enums instead of strings for value, in practice):

@Check(value="Type1", message="{type1.checkFailed}") public MyClass myVal1;
@Check(value="Type2", message="{type2.checkFailed}") public MyClass myVal2;

And that will get the end result I want. I can also implement multiple annotations/validators and do it this way and specify a default message in the definition of the annotation:

@CheckType1 public MyClass myVal1; // default message is type1.checkFailed
@CheckType2 public MyClass myVal2; // default message is type2.checkFailed

What I'd like to do is let the validator associated with @Check determine whether to use type1.checkFailed or type2.checkFailed as the message, depending on value, like this:

@Check("Type1") public MyClass myVal1;
@Check("Type2") public MyClass myVal2;

It is my understanding that the best practice is to keep a validator focused on a single characteristic. But I don't think what I'm trying to do is contrary to this since it is validation for a single characteristic, there are just variants of it that can be validated.

As an example using dog breeds:

@BreedSize("Large") Dog bigDog;
@BreedSize("Small") Dog smallDog;

Since a given annotation can only appear once on an element (at least as of SE7), this might also be a reasonable way to ensure only one of several mutually-exclusive validations take place. I think there was/is a proposal for multiple annotations of the same type on an element, but I suppose the validator could check that only one was supplied, in that case -- getting ahead of things here, though.

Is this possible?

4

1 回答 1

0

ConstraintValidatorContext您可以通过传递给这样的isValid()方法来创建自定义约束违规对象:

public class BreedSizeValidator implements ConstraintValidator<BreedSize, Dog> {

    private String value;

    @Override
    public void initialize(BreedSize constraintAnnotation) {
        this.value = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(
        Dog object,
        ConstraintValidatorContext constraintContext) {

        if ( object == null ) {
            return true;
        }

        boolean isValid = ...;

        if ( !isValid ) {
            String messageKey = "Large".equals( value ) ? 
                "{BreedSize.Large.message}" : "{BreedSize.Small.message}";

            constraintContext.disableDefaultConstraintViolation();
            constraintContext
                .buildConstraintViolationWithTemplate( messageKey )
                .addConstraintViolation();
        }

        return isValid;
    }
}
于 2013-07-20T16:34:22.007 回答