I have a bean with this validation:
@Email(message = "Email is not valid", regexp="{(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])}")
@NotEmpty(message = "Email cannot be empty")
private String email;
when the email is empty the message is fine, but when I enter this text
perisava.util.Random@1d7f0036
no error is shown
javax.validation.constraints.Email
annotation depends on Jakarta Bean Validation providers
for validation. Hibernate Validator is the only compliant validator for this.
By default hibernate vaildator matches the email to regex .*
unless you provide the regex yourself. Hibernate email validator source code is here.
One solution is to provide your own email regex
@Email(message = "Email is not valid", regexp = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$")
@NotEmpty(message = "Email cannot be empty")
private String email;
The official standard is RFC 5322. But it does not cover all cases for modern emails. You can find more solutions here. Even then regex would be up to you to decide.