Cross field validation with Hibernate Validator (JSR 303)

前端 未结 15 1780
渐次进展
渐次进展 2020-11-22 02:37

Is there an implementation of (or third-party implementation for) cross field validation in Hibernate Validator 4.x? If not, what is the cleanest way to implement a cross fi

15条回答
  •  走了就别回头了
    2020-11-22 02:46

    I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:

    import org.springframework.beans.BeanWrapper;
    import org.springframework.beans.PropertyAccessorFactory;
    
    import javax.validation.ConstraintValidator;
    import javax.validation.ConstraintValidatorContext;
    
    public class FieldMatchValidator implements ConstraintValidator {
    
        private String firstFieldName;
        private String secondFieldName;
    
        @Override
        public void initialize(final FieldMatch constraintAnnotation) {
            firstFieldName = constraintAnnotation.first();
            secondFieldName = constraintAnnotation.second();
        }
    
        @Override
        public boolean isValid(final Object object, final ConstraintValidatorContext context) {
    
            BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
            final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
            final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);
    
            boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
    
            if (!isValid) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode(firstFieldName)
                    .addConstraintViolation();
            }
    
            return isValid;
    
        }
    }
    

提交回复
热议问题