Abstract and regex

I need to do an email check using annotation + regex. I tried using the following:

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

However, I do not know how to print an error message when I have the wrong email address in the email field. Any ideas?

+5
source share
2 answers

You must first add the attribute messageto the annotation Pattern. Suppose your mail variable is part of some User class:

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

Then you should define a validator:

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

Then find the validation errors.

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

As stated in the comments above:

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

All Articles