Hibernate自定义验证器,如何设置propertyPath?

时间:2012-05-18 02:24:41

标签: java hibernate validation orm

我们已经实现了自定义验证程序。

我们收到的信息确定,但不是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;

1 个答案:

答案 0 :(得分:2)

在“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