如何为List创建ConstraintValidator

我有一个简单的validation器来validationString值是预定义列表的一部分:

public class CoBoundedStringConstraints implements ConstraintValidator { private List m_boundedTo; @Override public void initialize(CoBoundedString annotation) { m_boundedTo = FunctorUtils.transform(annotation.value(), new ToLowerCase()); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null ) { return true; } context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate("should be one of " + m_boundedTo).addConstraintViolation(); return m_boundedTo.contains(value.toLowerCase()); } } 

例如,它将validation:

 @CoBoundedString({"a","b" }) public String operations; 

我想创建一个validation器对于一个字符串列表来validation这样的东西:

 @CoBoundedString({"a","b" }) public List operations = new ArrayList(); 

我试过这个:

 public class CoBoundedStringListConstraints implements ConstraintValidator<CoBoundedString, List> { private CoBoundedString m_annotation; @Override public void initialize(CoBoundedString annotation) { m_annotation = annotation; } @Override public boolean isValid(List value, ConstraintValidatorContext context) { if (value == null ) { return true; } CoBoundedStringConstraints constraints = new CoBoundedStringConstraints(); constraints.initialize(m_annotation); for (String string : value) { if (!constraints.isValid(string, context)) { return false; } } return true; } } 

问题是,如果列表包含2个或更多的非法值,则只有一个(第一个)约束违规。 我希望它不止一个。 我该怎么做?

您当前的代码有2个问题:

在你的CoBoundedStringListConstraintsisValid方法中,你应该像这样迭代给定列表的所有元素(设置一个合适的allValid标志):

 @Override public boolean isValid(List 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; } 

第二个是约束违规的equals实现( javax.validation.Validator.validate()返回一个集合! )。 当您总是输入相同的消息( should be one of [a, b] )时,该集合仍将只包含1个元素。 作为解决方案,您可以将当前值添加到消息(类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; }