I have a simple validator to validate that a String value is part of a predefined list:
public class CoBoundedStringConstraints implements ConstraintValidat
There are 2 problems with your current code:
In your CoBoundedStringListConstraints
's isValid
method you should iterate over all elements of the given list like this (set a allValid
flag appropriate):
@Override
public boolean isValid(List<String> value,
ConstraintValidatorContext context) {
if (value == null) {
return true;
}
boolean allValid = true;
CoBoundedStringConstraints constraints = new CoBoundedStringConstraints();
constraints.initialize(m_annotation);
for (String string : value) {
if (!constraints.isValid(string, context)) {
allValid = false;
}
}
return allValid;
}
The second is the implementation of equals
for the constraint violation (javax.validation.Validator.validate()
returns a set!). When you are always putting in the same message (should be one of [a, b]
), the set will still contain only 1 element. As a solution you could prepend the current value to the message (class CoBoundedStringConstraints
):
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
if (!m_boundedTo.contains(value)) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
value + " should be one of " + m_boundedTo)
.addConstraintViolation();
return false;
}
return true;
}