annotation & regex

11

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

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

然而,当我在电子邮件字段中输入不正确的电子邮件地址时,我不知道如何打印错误消息。有什么想法吗?


1
那取决于您如何验证以及您想在哪里打印该消息。简单的答案:System.out.println(...) :) - Thomas
4
抱歉问这个问题,但为什么你不使用@Email注释? - Peterino
2个回答

17

首先,您应该向您的Pattern注释添加一个message属性。假设您的邮件变量是某个名为User的类的一部分:

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

那么你需要定义一个验证器:

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

然后查找验证错误。

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

2

正如上面的评论所提到的:

@NotNull
@Email(message = "This email address is invalid")
private String email;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接