英文:
Hibernate Validator - Dynamic Validation-Message
问题
我有一个名为X
的类,其中有三个字段:state
(一个枚举类型,可以是A
或B
)、a
和b
。
当state
为A
时,a
不能为null
;当state
为B
时,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 = "Validation failed")
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 "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;
}
}
}
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("message here");
Enjoy!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论