Hibernate 验证器:@Email 接受 ask@stackoverflow 作为有效吗? [英] Hibernate validator: @Email accepts ask@stackoverflow as valid?
问题描述
我正在使用 @Email
批注来验证电子邮件地址.我遇到的问题是它接受像 ask@stackoverflow
这样的东西作为有效的电子邮件地址.我猜这是因为他们想要支持 Intranet 地址,但我似乎找不到标志,因此它确实检查了扩展名.
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.
我真的需要切换到 @Pattern
(以及任何关于灵活的电子邮件模式的建议)还是我遗漏了什么?
Do I really need to switch to @Pattern
(and any recommendations for an e-mail pattern that's flexible) or am I missing something?
推荐答案
实际上,@Email
来自 Hibernate Validator 在内部使用正则表达式.您可以根据该正则表达式轻松定义自己的约束,并根据需要进行修改(注意 DOMAIN
末尾的 +
):
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
+ ")$";
}
这篇关于Hibernate 验证器:@Email 接受 ask@stackoverflow 作为有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!