Hibernate Validator – 动态验证消息

huangapple go评论82阅读模式
英文:

Hibernate Validator - Dynamic Validation-Message

问题

我有一个名为X的类,其中有三个字段:state(一个枚举类型,可以是AB)、ab
stateA时,a不能为null;当stateB时,b不能为null

使用 hibernate-validator,我已经构建了以下的验证器:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyValidator.class)
@Documented
public @interface ValidateCondition {
  String message() default "ValidateCondition failed";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}

public class MyValidator implements ConstraintValidator<ValidateCondition, X> {
  @Override
  public boolean isValid(X x, ConstraintValidatorContext context) {
    if (x.getState() == State.A) {
      return x.getA() != null;
    }
    if (x.getState() == State.B) {
      return x.getB() != null;
    }
  }
}

所以每当验证失败时,我当前会得到消息 Validation failed,但是我想要的是一条消息,告诉我为什么验证失败,比如 由于 state 为 B,b 不能为空

我认为我可以以某种方式使用 ConstraintValidatorContext 来实现这一点,但我不知道是否可行,以及如何实现。

英文:

I'm having a class X that has three fields: state (an enum of A and B), a and b.
When state is A, a must not be null, when state is B, b must not be null.

@ValidateCondition(message = &quot;Validation failed&quot;)
public class X {
  private State state;
  private String a;
  private String b;
}

Using hibernate-validator, I've build the following Validator:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyValidator.class)
@Documented
public @interface ValidateCondition {
  String message() default &quot;ValidateCondition failed&quot;;
  Class&lt;?&gt;[] groups() default {};
  Class&lt;? extends Payload&gt;[] payload() default {};
}

public class MyValidator implements ConstraintValidator&lt;ValidateCondition, X&gt; {
  @Override
  public boolean isValid(X x, ConstraintValidatorContext context) {
    if(x.getState()==State.A){
      return x.getA() != null;
    }
    if(x.getState()==State.B){
      return x.getB() != null;
    }
  }
}

So whenever validation fails, I currently get the message Validation failed, but what I want would be a message, telling me why it failed, like Since state was B, b must not be blank.

I'm assuming I can somehow use the ConstraintValidatorContext for that, but I don't know if or how.

答案1

得分: 2

这很简单:
只需在isValid区域内调用一个上下文:

context.buildConstraintViolationWithTemplate("在此处添加消息");

享受!

英文:

It's quite simple:
Just call a context inside isValid area:

context.buildConstraintViolationWithTemplate(&quot;message here&quot;);

Enjoy!

huangapple
  • 本文由 发表于 2020年9月24日 19:18:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64045360.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定