Java – JSR 303 custom constraint override
I want to place a set of standard constraints (such as a non empty alphanumeric string with a length of 3 to 240 characters) on the field (in this case, a string) and wonder if there is a way to override some constraints in the model code Will this also be a rewrite, or will it just validate the overridden comments twice?
It should be like this
@AlphanumericString @Size(min=100,max=150) //override standart values from AlphanumericString annotation
Thank you for your answer
OK, answer myself@ Overridesparameter helps to reassign nested annotation parameters
@Numerical @Size //arbitrary parameter values @ConstraintValidator(FrenchZipcodeValidator.class) @Documented @Target({ANNOTATION_TYPE,METHOD,FIELD}) @Retention(RUNTIME) public @interface FrenchZipCode { String message() default "Wrong zipcode"; String[] groups() default {}; @OverridesParameters( { @OverridesParameter(constraint=Size.class,parameter="min") @OverridesParameter(constraint=Size.class,parameter="max") } ) int size() default 5; @OverridesParameter(constraint=Size.class,parameter="message") String sizeMessage() default "{error.zipcode.size}"; @OverridesParameter(constraint=Numerical.class,parameter="message") String numericalMessage() default "{error.zipcode.numerical}"; }
source
Solution
This is a good question JSR 303 bean validation specification describes the validation routines in section 3.5
In your case, you will handle validation of a simple string field with a target group of default You have two validation constraints (@ alphanumericstring and @ size), which will be validated / processed separately in a specific order according to the document
So answer your question No, when you use @ size addaly, @ alphanumericstring does not apply any overrides To achieve what I think you are trying to do, you can create a constraint combination where you can override attributes from the composition annotation:
@Pattern(regexp="[a-zA-Z]*") @Size @Constraint(validatedBy = AlphanumericStringValidator.class) @Documented @Target({ METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER }) @Retention(RUNTIME) public @interface AlphanumericString { // ... @OverridesAttribute(constraint=Size.class,name="min") int min() default 3 @OverridesAttribute(constraint=Size.class,name="max") int max() default 230; // ... }
And use it:
@AlphanumericString(min = 100,max = 150)