I'm using the @Email
annotation to validate an e-mail address.
The issue I'm having is that it's accepting things like ask@stackoverflow
as a valid e-mail address.
I guess this is because they want to support intranet addresses, but I can't seem to find a flag so it does check for an extension.
Do I really need to switch to @Pattern
(and any recommendations for an e-mail pattern that's flexible) or am I missing something?
Actually, @Email
from Hibernate Validator uses regexp internally. You can easily define your own constraint based on that regexp, modified as you need (note the +
at the end of DOMAIN
):
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@Pattern(regexp = Constants.PATTERN, flags = Pattern.Flag.CASE_INSENSITIVE)
public @interface EmailWithTld {
String message() default "Wrong email";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
interface Constants {
static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
static final String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)+";
static final String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";
static final String PATTERN =
"^" + ATOM + "+(\\." + ATOM + "+)*@"
+ DOMAIN
+ "|"
+ IP_DOMAIN
+ ")$";
}