ConditionalValidator icon indicating copy to clipboard operation
ConditionalValidator copied to clipboard

ConditionalValidator fails if valid exists after the invalid one

Open bsimakis opened this issue 8 years ago • 2 comments

When validating multiple fields are required, there are valid fields after the invalid ones, the isValid method incorrectly returns true. Change method to:

public boolean isValid(Object object, ConstraintValidatorContext context) {
    Boolean valid = true;
    try {
        Object checkedValue = BeanUtils.getProperty(object, selected);
        if (Arrays.asList(values).contains(checkedValue)) {
            for (String propName : required) {
                Object requiredValue = BeanUtils.getProperty(object, propName);
                boolean propValid = requiredValue != null && !isEmpty(requiredValue);
                if (!propValid) {
                    valid = false;
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate(message).addPropertyNode(propName).addConstraintViolation();
                }
            }
        }
    } catch (IllegalAccessException e) {
        log.error("Accessor method is not available for class : {}, exception : {}", object.getClass().getName(), e);
        e.printStackTrace();
        return false;
    } catch (NoSuchMethodException e) {
        log.error("Field or method is not present on class : {}, exception : {}", object.getClass().getName(), e);
        e.printStackTrace();
        return false;
    } catch (InvocationTargetException e) {
        log.error("An exception occurred while accessing class : {}, exception : {}", object.getClass().getName(), e);
        e.printStackTrace();
        return false;
    }
    return valid;
}

bsimakis avatar Jan 06 '18 23:01 bsimakis

Was coming to create the same ticket.

TehBakker avatar Oct 28 '19 12:10 TehBakker

also change test to reflect this behavior

enaira-q avatar Jan 29 '24 13:01 enaira-q