本文介绍了简单的电子邮件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试做一个非常简单的电子邮件验证。但是问题是当我尝试使用 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 = "[email protected]";
// 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并使用其。
Or cease from reinventing the wheel, grab Apache Commons and use its EmailValidator
.
这篇关于简单的电子邮件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!