如何为List创建ConstraintValidator

时间:2011-10-23 08:51:06

标签: java hibernate list bean-validation

我有一个简单的验证器来验证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;
}

}

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

1 个答案:

答案 0 :(得分:3)

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

CoBoundedStringListConstraints的{​​{1}}方法中,您应该像这样迭代给定列表的所有元素(设置适当的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())时,该集合仍将只包含1个元素。作为解决方案,您可以将当前值添加到消息(类should be one of [a, b]):

CoBoundedStringConstraints