Hibernate Validator 5.3 中的自定义验证,无需实现 ConstraintValidator

问题描述

在不实施ConstraintValidator的情况下,添加使用Hibernate Validator的自定义验证的正确方法是什么。

我以某种方式设法实现了它:-

认约束验证:-

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();

//validating Bean
     Set<ConstraintViolation<Object>> constraintViolations = this.validator.validate(opts);
            if(constraintViolations.size() > 0)
                throw new BeanValidationException(constraintViolations);

对于自定义验证和认值:-

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
    
//validating Bean
Set<ConstraintViolation<Object>> constraintViolations = this.validator.validate(opts);

//从集合创建列表

List<String> invalid = new ArrayList<>();
  constraintViolations.stream().forEach((t) -> {
  invalid.add(t.getMessage());
});

//添加自定义 bean Validaiton 消息

if(thisHappens){
  invalid.add("validationError");
}
if(thisHappens){
  invalid.add("validationError");
}
if(thisHappens){
  invalid.add("validationError");
}

//thorwing exception
if(!invalid.isEmpty(){
  throw new BeanValidationException(invalid);
}

BeanValidationException.class

public class BeanValidationException extends RuntimeException {

    private final Set<ConstraintViolation<Object>> defaultViolations;
    private final List<String> customViolations;

    public BeanValidationException(Set<ConstraintViolation<Object>> constraintViolations) {
        this.defaultViolations = constraintViolations;
        this.customViolations = null;
    }

    public BeanValidationException(List<String> customViolations) {
        this.customViolations = customViolations;
        this.defaultViolations = null;
    }

    public String getValidationError() {

        String message = "";

        if (this.defaultViolations != null) {

            if (!this.defaultViolations.isEmpty()) {
                for (ConstraintViolation violationMsg : defaultViolations) {
                    if (!message.contains(violationMsg.getMessage())) {
                        message += " " + '\u2022' + " " + violationMsg.getMessage() + "\n";
                    }
                }
            }
            return message;
        } else {
            if (!this.customViolations.isEmpty()) {
                for (String violationMsg : customViolations) {
                    if (!message.contains(violationMsg)) {
                        message += " " + '\u2022' + " " + violationMsg + "\n";
                    }
                }
            }
            return message;
        }
    }
}

并且从 getValidationError() 我收到所有验证违规消息。这是正确/推荐的方式吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)