Bean Interpolation of validation messages with an array constraint parameter, used as a variable in the message
Is it possible to concatenate int array arguments in javax.validation error message interpolation?
I want to test a string for different possible lengths and I started implementing a custom constraint:
@Constraint(validatedBy = {BarcodeValidator.class})
public @interface Barcode {
String message() default "{validation.Barcode.message}";
int[] lengths();
}
Validator:
public class BarcodeValidator implements ConstraintValidator<Barcode, String> {
private List<Integer> lengths;
@Override
public void initialize(Barcode barcode) {
lengths = new ArrayList<>(barcode.lengths().length);
for (int l : barcode.lengths()) lengths.add(l);
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && lengths.contains(value.length());
}
}
I would like to create a custom message for it: Barcode must be 12/23/45 characters long!
I realized I could use the annotation options in the post, so I would like to do something like:
validation.Barcode.message = The barcode must be ${'/'.join(lengths)} character long!
Is something like this possible or should I be doing it in some other way?
(PS: My first question is here on SO.)
+3
source to share
1 answer
I eventually found a solution.
Validator class:
public class BarcodeValidator implements ConstraintValidator<Barcode, String> {
private List<Integer> lengths;
@Override
public void initialize(Barcode barcode) {
lengths = new ArrayList<>(barcode.lengths().length);
for (int l : barcode.lengths()) lengths.add(l);
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
context.unwrap(HibernateConstraintValidatorContext.class).addExpressionVariable("joinedLengths", String.join(" / ", lengths));
return value != null && lengths.contains(value.length());
}
}
* properties :.
validation.Barcode.message = The barcode must be ${joinedLengths} character long!
Also tried to give a name to the parameter lengths
, but that didn't work - it might be related to the type int[]
.
+3
source to share