你可以这样做:
@NotNull(message="First name {err.required}")
@Size(min=1, message="First name {err.required}")
private String firstName;
@NotNull(message="Last name {err.required}")
@Size(min=1, message="Last name {err.required}")
private String lastName;
并在属性文件中
err.required= is required.
或者如果您想更清楚,您可以添加自己的注释和验证器:
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { NotEmptyValidator.class })
public @interface NotEmpty {
String message() default "{customMessage} is required.";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String customMessage() default "";
}
public class NotEmptyValidator implements ConstraintValidator<NotEmpty, String>
{
@Override
public void initialize(NotEmpty notEmpty)
{
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context)
{
return value != null && !value.isEmpty();
}
}
然后你的领域
@NotEmpty(message="{err.required}"
customMessage="First name")
private String firstName;
在属性中(尽管它不是强制性的,因为您可以将值默认为这个):
err.required={customMessage} is required.