Spring Validation - Class level validation to address field errors

好久不见. 提交于 2019-12-05 18:30:38

Damn you, Spring documentation! It is fairly simple, but not really understandable.

@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
    if (fields.length > 0) {
        final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(value);
        final Object comparisonValue = beanWrapper.getPropertyValue(fields[0]);

        for (int i = 1; i < fields.length; i++) {
            if (!comparisonValue.equals(beanWrapper.getPropertyValue(fields[i]))) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(errorMessage).addPropertyNode(fields[0]).addConstraintViolation();
                return false;
            }
        }
    }

    return true;
}

The method disableDefaultConstraintViolation() tells the ConstrainValidatorContext to not produce the constraint violation object by using the annotation itself.

You can then produce a custom constraint violation via the buildConstraintViolationWithTemplate() method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!