如何为列表创建ConstraintValidator

我有一个简单的验证器来验证String值是否是预定义列表的一部分:

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;

}

}

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

回答:

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

在您CoBoundedStringListConstraintsisValid方法中,您应该像这样遍历给定列表的所有元素(设置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针对约束违反的实现( )。当您始终输入相同的消息(should be one of [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;

}

以上是 如何为列表创建ConstraintValidator 的全部内容, 来源链接: utcz.com/qa/403705.html

回到顶部