Hibernate验证器:@Email接受ask @ stackoverflow为有效的? [英] Hibernate validator: @Email accepts ask@stackoverflow as valid?

查看:105
本文介绍了Hibernate验证器:@Email接受ask @ stackoverflow为有效的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 @Email 注释来验证电子邮件地址。
我遇到的问题是它接受诸如 ask @ stackoverflow 之类的东西作为有效的电子邮件地址。
我想这是因为他们想要支持Intranet地址,但我似乎无法找到一个标志,因此它检查扩展名。



我真的需要切换到 @Pattern (以及对灵活的电子邮件模式的任何建议)还是我错过了什么?

@Email 解决方案 hibernate-validator / blob / master / engine / src / main / java / org / hibernate / validator / internal / constraintvalidators / EmailValidator.java?source = cc>在内部使用regexp 。您可以根据该regexp轻松定义自己的约束,并根据需要进行修改(请注意结尾处的 + > 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( )默认的错误的电子邮件;
Class<?> [] groups()default {};
Class <?扩展了Payload> [] payload()default {};
}

接口常量{
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
+)$;
}


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
                    + ")$";
}

这篇关于Hibernate验证器:@Email接受ask @ stackoverflow为有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆