【发布时间】:2011-10-23 08:51:06
【问题描述】:
我有一个简单的验证器来验证字符串值是否是预定义列表的一部分:
public class CoBoundedStringConstraints implements ConstraintValidator<CoBoundedString, String>
{
private List<String> 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());
}
}
例如它将验证:
@CoBoundedString({"a","b" })
public String operations;
我想为字符串列表创建一个验证器来验证类似这样的内容:
@CoBoundedString({"a","b" })
public List<String> operations = new ArrayList<String>();
我试过了:
public class CoBoundedStringListConstraints implements ConstraintValidator<CoBoundedString, List<String>>
{
private CoBoundedString m_annotation;
@Override
public void initialize(CoBoundedString annotation)
{
m_annotation = annotation;
}
@Override
public boolean isValid(List<String> 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 个或更多非法值,则只会出现一个(第一个)约束违规。我希望它有不止一个。我该怎么做?
【问题讨论】:
-
我找到了一个可能的解决方案:stackoverflow.com/questions/4308224/…。但是,没能成功。
标签: java hibernate list bean-validation