how to create a ConstraintValidator for List

前端 未结 1 529
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 05:16

I have a simple validator to validate that a String value is part of a predefined list:

public class CoBoundedStringConstraints implements ConstraintValidat         


        
相关标签:
1条回答
  • 2020-12-17 05:44

    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;
    }
    
    0 讨论(0)
提交回复
热议问题