how to create a ConstraintValidator for List

寵の児 提交于 2019-11-29 05:05:38

There are 2 problems with your current code:

In your CoBoundedStringListConstraints's isValid method you should iterate over all elements of the given list like this (set a allValid flag appropriate):

@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;
}

The second is the implementation of equals for the constraint violation (javax.validation.Validator.validate() returns a set!). When you are always putting in the same message (should be one of [a, b]), the set will still contain only 1 element. As a solution you could prepend the current value to the message (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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!