首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Hibernate自定义验证器,如何设置propertyPath?

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

Stack Overflow用户
提问于 2012-05-18 10:24:41
回答 1查看 3.7K关注 0票数 3

我们实现了一个自定义的Validator。

我们得到的消息是好的,但不是propertyPath,我们怎么能把它拉回来呢?

我们对象中的实现

代码语言:javascript
复制
@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")
})

//约束类

代码语言:javascript
复制
@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();
    }
}

//我们遍历无效字段的位置

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2012-12-12 17:58:04

在你的"RequiredIfSetValidator“中,在isValid方法中添加如下内容:

代码语言:javascript
复制
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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10645975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档