Java中有哪些好的电子邮件地址验证库?有任何替代公共验证器的方法吗?


当前回答

当前的Apache Commons Validator版本为1.3.1。

进行验证的类是org.apache.commons.validator.EmailValidator。它导入了org.apache.oro.text.perl。Perl5Util来自一个退役的雅加达ORO项目。

BTW, I found that there is a 1.4 version, here are the API docs. On the site it says: "Last Published: 05 March 2008 | Version: 1.4-SNAPSHOT", but that's not final. Only way to build yourself (but this is a snapshot, not RELEASE) and use, or download from here. This means 1.4 has not been made final for three years (2008-2011). This is not in Apache's style. I'm looking for a better option, but didn't find one that is very adopted. I want to use something that is well tested, don't want to hit any bugs.

其他回答

您想验证什么?电子邮件地址?

只能检查电子邮件地址的格式是否符合要求。参见标准:RFC2822。最好的方法是使用正则表达式。如果不发一封邮件,你永远不会知道是否真的存在。

我检查了公共验证器。它包含一个org.apache.commons.validator.EmailValidator类。看起来是个不错的起点。

这是最好的方法:

public static boolean isValidEmail(String enteredEmail){
        String EMAIL_REGIX = "^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$";
        Pattern pattern = Pattern.compile(EMAIL_REGIX);
        Matcher matcher = pattern.matcher(enteredEmail);
        return ((!enteredEmail.isEmpty()) && (enteredEmail!=null) && (matcher.matches()));
    }

来源: http://howtodoinjava.com/2014/11/11/java-regex-validate-email-address/

http://www.rfc-editor.org/rfc/rfc5322.txt

Les Hazlewood使用Java正则表达式编写了一个非常完整的符合RFC 2822的电子邮件验证器类。你可以在http://www.leshazlewood.com/?p=23上找到它。然而,它的彻底性(或Java RE实现)导致效率低下——阅读关于长地址解析时间的注释。

当前的Apache Commons Validator版本为1.3.1。

进行验证的类是org.apache.commons.validator.EmailValidator。它导入了org.apache.oro.text.perl。Perl5Util来自一个退役的雅加达ORO项目。

BTW, I found that there is a 1.4 version, here are the API docs. On the site it says: "Last Published: 05 March 2008 | Version: 1.4-SNAPSHOT", but that's not final. Only way to build yourself (but this is a snapshot, not RELEASE) and use, or download from here. This means 1.4 has not been made final for three years (2008-2011). This is not in Apache's style. I'm looking for a better option, but didn't find one that is very adopted. I want to use something that is well tested, don't want to hit any bugs.

下面是我的实用方法,我只需要使用RFC中允许的字符合理地区分blah@domain地址。地址必须事先转换为小写。

public class EmailAddressValidator {

    private static final String domainChars = "a-z0-9\\-";
    private static final String atomChars = "a-z0-9\\Q!#$%&'*+-/=?^_`{|}~\\E";
    private static final String emailRegex = "^" + dot(atomChars) + "@" + dot(domainChars) + "$";
    private static final Pattern emailPattern = Pattern.compile(emailRegex);

    private static String dot(String chars) {
        return "[" + chars + "]+(?:\\.[" + chars + "]+)*";
    }

    public static boolean isValidEmailAddress(String address) {
        return address != null && emailPattern.matcher(address).matches();
    }

}