我已经编写了自定义字符串数组验证器:
@Documented
@Constraint(validatedBy = KeyArrayValidator.class)
@Target( { ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface KeyArrayValid {
String message() default "array is null, array is empty or there are wrong keys";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
public class KeyArrayValidator implements ConstraintValidator<KeyArrayValid, String[]> {
@Override
public boolean isValid(String[] value, ConstraintValidatorContext context) {
boolean valid = false;
if (value != null && value.length > 0) {
valid = true;
for (String oneVal: value) {
if (!oneVal.matches("^([A-Za-z0-9]+[\\s,.;:?!]*)+$")) {
valid = false;
break;
}
}
}
return valid;
}
}
它做得很好,但是我希望它生成更具体的消息,例如“键{这里错误的键}包含错误的字符”。
有可能吗?如果可以,怎么办?