问题
Possible Duplicate:
Verify email in Java
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.
Here are the codes:
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;
}
Please help. Thanks in advance.
回答1:
.+@.+
will match anything, including @
, followed by @
, followed by anything, including @
. Use [^@]+@[^@]+
instead.
Or cease from reinventing the wheel, grab Apache Commons and use its EmailValidator.
回答2:
You can use the class javax.mail.internet.InternetAddress from the Javamail API (there is a validate
method)
回答3:
This is a solved problem in numerous libraries. Do not reimplement your own.
Getting this 100% correct in regexps is much, much harder than you think it is.
回答4:
This site suggests that the following pattern matches RFC 5322 and covers most email addresses used today:
Pattern p = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", Pattern.CASE_INSENSITIVE);
It worked for a few quick tests that I made.
Consider storing the compiled pattern in a constant for improved performance.
回答5:
It should be Pattern p = Pattern.compile(".+@{1}+\\.[a-z]+");
BUT:
This my answer above is wrong exactly like the answer @larsmans, because:
this(comment)me@demo.com is a valid email.
You have to read the RFC: http://tools.ietf.org/html/rfc5322
In fact, use a good library, as apache-commons.
来源:https://stackoverflow.com/questions/8259790/simple-email-validation