您可以通过更改注释来提供字段描述,然后在验证程序中公开此信息。
首先,description
字段添加到您的注释:
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EmptyCheckValidator.class)
@Documented
public @interface EmptyCheck {
String description() default "";
String message() default "{empty.check}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
其次,改变你的消息,以便它使用一个命名的参数;这更可读。
empty.check= Please enter ${description}
由于您使用的是hibernate-validator,因此您可以在验证类中获取hibernate验证程序上下文并添加上下文变量。
public class EmptyCheckValidator
implements ConstraintValidator<EmptyCheck, String> {
String description;
public final void initialize(final EmptyCheck annotation) {
this.description = annotation.description();
}
public final boolean isValid(final String value,
final ConstraintValidatorContext context) {
if(null != value && !value.isEmpty) {
return true;
}
HibernateConstraintValidatorContext ctx =
context.unwrap(HibernateConstraintValidatorContext.class);
ctx.addExpressionVariable("description", this.description);
return false;
}
}
最后,说明添加到字段:
@EmptyCheck(description = "a user name") private String userName
当用户名为空或空这将产生以下错误:
Please enter a user name
@ beerbajay感谢重播。但是,如果消息中有多个参数,例如empty.check =请输入{0} {1}。我们如何实现..? –
@ShashiDk您可以使用不同的变量名称多次调用'addExpressionVariable'。从哪里获取这些参数? – beerbajay