Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

annotation & regex

I need to do a validation of an e-mail using annotation + regex. I tried to use the following:

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

However, I don't know how to print an error message when I have an incorrect e-mail address in the email field. Any ideas?

like image 303
Steffi Avatar asked Apr 02 '12 14:04

Steffi


People also ask

What is an annotation example?

a student noting examples or quotes in the margins of a textbook. a reader noting content to be revisited at a later time. a Bible reader noting sources in their Bible of relevant verses for study. an academic noting similar or contradictory studies related to their article or book.

What is the meaning to annotate?

Definition of annotate intransitive verb. : to make or furnish critical or explanatory notes or comment. transitive verb. : to make or furnish annotations (see annotation sense 1) for (something, such as a literary work or subject) annotated his translation of Dante's Divine Comedy.

What does annotation mean in writing?

Annotation is a written conversation between you and the writer in which you actively respond to the text. Pretend you are talking to the writer as you read. This exercise will help you to find connections between ideas in the text and ideas in other sources.

What is the purpose of a annotation?

What is Annotating? Annotating is any action that deliberately interacts with a text to enhance the reader's understanding of, recall of, and reaction to the text. Sometimes called "close reading," annotating usually involves highlighting or underlining key pieces of text and making notes in the margins of the text.


1 Answers

First you should add a message attribute to your Pattern annotation. Assume that your mail variable is part of some class User:

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("[email protected]");
Set<ConstraintViolation<User>> constraintViolations = validator
        .validate(user);

Then find 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()));
}
like image 165
Alex Stybaev Avatar answered Oct 16 '22 16:10

Alex Stybaev