我有一个简单的 validator 来验证一个字符串值是预定义列表的一部分:
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;
我想为字符串列表创建一个 validator 来验证这样的东西:
@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 个或更多非法值,则只有一个(第一个)违反约束。我希望它有多个。我应该怎么做?
最佳答案
您当前的代码有两个问题:
在您的 CoBoundedStringListConstraints
的 isValid
方法中,您应该像这样迭代给定列表的所有元素(适当设置一个 allValid
标志) :
@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;
}
第二个是equals
的实现,用于违反约束(javax.validation.Validator.validate()
返回一个集合!) .当您始终输入相同的消息时(应该是 [a, b] 之一
),该集合仍将仅包含 1 个元素。作为一种解决方案,您可以将当前值添加到消息中(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;
}
关于java - 如何为 List 创建一个 ConstraintValidator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7865209/