ConditionalValidator
ConditionalValidator copied to clipboard
ConditionalValidator fails if valid exists after the invalid one
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;
}
Was coming to create the same ticket.
also change test to reflect this behavior