Validator中为每个属性生成错误代码

Validator中为每个属性生成错误代码

本文介绍了在Hibernate Validator中为每个属性生成错误代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用Hibernate Validator来满足我的要求.我想验证一个JavaBean,其中的属性可能具有多个验证检查.例如:

I am looking at using Hibernate Validator for a requirement of mine. I want to validate a JavaBean where properties may have multiple validation checks. For example:

class MyValidationBean
{
   @NotNull
   @Length( min = 5, max = 10 )
   private String myProperty;
}

但是如果此属性验证失败,我希望将特定的错误代码与ConstraintViolation关联,无论它是由于@Required还是@Length而失败,尽管我想保留错误消息.

But if this property fails validation I want a specific error code to be associated with the ConstraintViolation, regardless of whether it failed because of @Required or @Length, although I would like to preserve the error message.

class MyValidationBean
{
   @NotNull
   @Length( min = 5, max = 10 )
   @ErrorCode( "1234" )
   private String myProperty;
}

类似上面的东西会很好,但是不必完全那样构造.我看不到使用Hibernate Validator执行此操作的方法.有可能吗?

Something like the above would be good but it doesn't have to be structured exactly like that. I can't see a way to do this with Hibernate Validator. Is it possible?

推荐答案

您可以创建一个自定义批注以获取所需的行为,然后在验证和使用反射时可以提取批注的值.类似于以下内容:

You could create a custom annotation to get the behaviour you are looking for and then on validating and using refelection you could extract the value of the annotation. Something like the following:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ErrorCode {
    String value();
}

在您的bean中:

@NotNull
@Length( min = 5, max = 10 )
@ErrorCode("1234")
public String myProperty;

在验证您的bean时:

On validating your bean:

Set<ConstraintViolation<MyValidationBean>> constraintViolations = validator.validate(myValidationBean);
for (ConstraintViolation<MyValidationBean>cv: constraintViolations) {
    ErrorCode errorCode = cv.getRootBeanClass().getField(cv.getPropertyPath().toString()).getAnnotation(ErrorCode.class);
    System.out.println("ErrorCode:" + errorCode.value());
}

已经说过,我可能会问这些类型的消息需要错误代码的要求.

Having said that I probably would question the requirements for wanting error codes for these types of messages.

这篇关于在Hibernate Validator中为每个属性生成错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:11