2

I have a column in database of length 512. It is going to contain multiple email address separated by ";". How can I validate its respective variable in the entity so that all the email address are valid.

List will not work as I need to persist it in the column. Here is the data:

@Basic
@Column(name = "CC_EMAIL_ADDRESS", nullable = true, length = 512)
private String emailCC;
Rosey Khatun
  • 89
  • 2
  • 9

5 Answers5

1

Use the javax.validation library. This will throw a validation exception if it fails to validate when you set attempt to persist the email, or you can do manual validation with starting with a ValidatorFactory.

@NotNull(message="{email.required}")
@Pattern(regexp = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
        + "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@"
        + "(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9]"
        + "(?:[A-Za-z0-9-]*[A-Za-z0-9])?",
        message = "{invalid.email}")
private String email;
K.Nicholas
  • 10,956
  • 4
  • 46
  • 66
1

This way I use with good success in my Projects

@NotEmpty
@Email
@Size(max = 255)
@Column(unique = true)
private String email;


@PrePersist
@PreUpdate
private void prepareData(){
    this.email = email == null ? null : email.toLowerCase();
}
Java bee
  • 2,522
  • 1
  • 12
  • 25
  • Code-only answers are considered low quality: make sure to provide an explanation what your code does and how it solves the problem. It will help the asker and future readers both if you can add more information in your post. See also Explaining entirely code-based answers: https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers – borchvm Oct 23 '19 at 06:46
0

You can use @PrePersist Callback event in your entity to valdiate the email before saving it to database.

@PrePersist
public void validateEmails(){
    //Validate Here
}

Or you can make a setter method in your Entity and validate the data in setter method.

0

You can create a custom constraint.

@MyCustomConstraint
private String emailCC;

where @MyCustomConstraint will be your new annotation.

Alex
  • 11,451
  • 6
  • 37
  • 52
0

Use been validation and a regex:

@Basic
@Pattern(regexp = "\\w+@\\w+\\.\\w+(,\\s*\\w+@\\w+\\.\\w+)*")
@Column(name = "CC_EMAIL_ADDRESS", nullable = true, length = 512)
sechanakira
  • 243
  • 3
  • 11