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


当前回答

这是最好的方法:

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

其他回答

当前的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.

Apache Commons通常被认为是一个可靠的项目。但是请记住,如果你想确保它是一个真实的电子邮件,并且所有者希望它在你的网站上使用,你仍然需要发送一封验证邮件到这个地址。

编辑:有一个错误,它对域名的限制太大,导致它不接受来自新顶级域名的有效电子邮件。 此错误已于03/Jan/15 02:48在common -validator版本1.4.1中解决

另一种选择是使用Hibernate电子邮件验证器,使用注释@Email或以编程方式使用验证器类,例如:

import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; 

class Validator {
    // code
    private boolean isValidEmail(String email) {
        EmailValidator emailValidator = new EmailValidator();
        return emailValidator.isValid(email, null);
    }

}

回答迟了,但我觉得简单而有价值:

    public boolean isValidEmailAddress(String email) {
           String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
           java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
           java.util.regex.Matcher m = p.matcher(email);
           return m.matches();
    }

测试用例:

出于生产目的,域名验证应该在网络上执行。

我只是想知道为什么没有人从Hibernate Validator的附加约束中想出@Email。验证器本身就是EmailValidator。