java - Hibernate自定义 validator ,如何设置propertyPath?

标签 java hibernate validation orm

我们已经实现了自定义 validator 。

我们可以正常返回消息,但不能返回 propertyPath,我们如何才能将其返回?

在我们的对象中实现

@RequiredIfSet.List({
        @RequiredIfSet(propertyPath = "reporterFirstName", field = "isFillingOutForSomeoneElse", dependentField = "reporterFirstName", message = "Reporter First may not be null"),
        @RequiredIfSet(propertyPath = "reporterLastName", field = "isFillingOutForSomeoneElse", dependentField = "reporterLastName", message = "Reporter Last may not be null"),
        @RequiredIfSet(propertyPath = "reporterContactPhone", field = "isFillingOutForSomeoneElse", dependentField = "reporterContactPhone", message = "Reporter Contact Phone may not be null"),
        @RequiredIfSet(propertyPath = "reporterEmail", field = "isFillingOutForSomeoneElse", dependentField = "reporterEmail", message = "Reporter Email may not be null")
})

//约束类

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy = RequiredIfSetValidator.class)
public @interface RequiredIfSet {
    String field();
    String dependentField();

    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    String message() default "Field Required";
    String propertyPath() default "";

    @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List {
        RequiredIfSet[] value();
    }
}

//我们循环无效字段

List<String[]> invalidFields = new ArrayList<String[]>();
        Iterator<ConstraintViolation<T>> iterator = cv.iterator();
        while(iterator.hasNext()) {
            ConstraintViolation<T> i = iterator.next();
            String property = i.getPropertyPath().toString();
            String message = i.getMessage();
            invalidFields.add(new String[] { property, message });
        }
        EntityValidationDTO EVDTO = new EntityValidationDTO();
        EVDTO.setStatus("fail");
        EVDTO.setInvalidFields(invalidFields);
        return EVDTO;

最佳答案

在“RequiredIfSetValidator”中,在方法 isValid 中添加如下内容:

if( !valid ) {
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addNode("fieldName").addConstraintViolation();
}

这里是官方文档:http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html#example-custom-error

关于java - Hibernate自定义 validator ,如何设置propertyPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10645975/

相关文章:

java - 为什么一对一双向关联需要LEFT OUTER Join

java - 孙子对象未更新

ruby-on-rails - 验证一批更新

java - 欧拉项目解决方案 #3 (Java) : Debugging

java - ActionBarSherlock 类型 mAdded 无法解析或不是字段 Watson.java

java - 如何在 Java 中以编程方式合并 EMF 模型?

java - 合并从 <util :properties> with Properties defined from <props> element 加载的属性

java - API Twitter 速率限制

wpf - 在样式中分配 ValidatesOnDataErrors

asp.net-mvc - 在 AJAX 请求之前单击按钮的客户端验证