简单的电子邮件验证 [英] Simple email validation

查看:104
本文介绍了简单的电子邮件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用Java验证电子邮件

我正在尝试做一个非常简单的电子邮件验证。但是问题是当我尝试使用 tom @@@@@ gmail.com 之类的方法时,它会返回true。

I'm trying to do a very simple email validation. But the problem is when I try something like tom@@@@gmail.com it returns true.

这里代码如下:

public static boolean validateEmail(String email){
        boolean isValidEmail = false;
       // Input the string for validation
       // String email = "xyz@.com";
       // Set the email pattern string
       Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

       // Match the given string with the pattern
       Matcher m = p.matcher(email);

       // check whether match is found
       boolean matchFound = m.matches();

       StringTokenizer st = new StringTokenizer(email, ".");
       String lastToken = null;
       while (st.hasMoreTokens()) {
          lastToken = st.nextToken();
       }

       if (matchFound && lastToken.length() >= 2
          && email.length() - 1 != lastToken.length()) {


          // validate the country code
          isValidEmail = true;
       }
       else isValidEmail = false;

    return isValidEmail;
}

请帮助。

推荐答案

。+ @。+ 会匹配任何内容,包括 @ ,然后是 @ ,然后是任何内容,包括 @ 。改为使用 [^ @] + @ [^ @] +

.+@.+ will match anything, including @, followed by @, followed by anything, including @. Use [^@]+@[^@]+ instead.

或者停止重新发明轮子,抓住Apache Commons并使用其 EmailValidator

Or cease from reinventing the wheel, grab Apache Commons and use its EmailValidator.

这篇关于简单的电子邮件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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