注释和正则表达式

Ste*_*ffi 8 java regex annotations

我需要使用注释+正则表达式验证电子邮件.我试着使用以下内容:

@NotNull
@Pattern(regexp=".+@.+\\.[a-z]+")
private String email;
Run Code Online (Sandbox Code Playgroud)

但是,当我在电子邮件字段中有不正确的电子邮件地址时,我不知道如何打印错误消息.有任何想法吗?

Ale*_*aev 14

首先,您应该messagePattern注释添加属性.假设您的邮件变量是某些类User的一部分:

class User{
@NotNull
@Pattern(regexp=".+@.+\\.[a-z]+", message="Invalid email address!")
private String email;
}
Run Code Online (Sandbox Code Playgroud)

然后你应该定义一个验证器:

ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
User user = new User();
user.setEmail("user@gmail.com");
Set<ConstraintViolation<User>> constraintViolations = validator
        .validate(user);
Run Code Online (Sandbox Code Playgroud)

然后找到验证错误.

for (ConstraintViolation<Object> cv : constraintViolations) {
      System.out.println(String.format(
          "Error here! property: [%s], value: [%s], message: [%s]",
          cv.getPropertyPath(), cv.getInvalidValue(), cv.getMessage()));
}
Run Code Online (Sandbox Code Playgroud)