开发者

Non-Confusing Simple Validation of email in Java String

I am trying to find a simple method to check to see if a user's input meets a couple criteria for an email address. I've read through many threads on this subject and most seem to want to validate the email address too. I'm not trying to build some super duper email address validator/checker. I'm trying to build a method that checks for these things:

  1. The string entered by the user contains the '@' sign.
  2. There are at least two characters before the '@' sign.
  3. There is a '.' after the at sign followed by only three characters. The domain name can be as long as needed, but the string must end with "._ _ _". As in ".com" or ".net"...

I understand that this is not an all encompassing email address checker. That's not what I want though. I want just something this simple. I know that this is probably a routine question but I can't figure it out even after reading all of the seriously crazy开发者_StackOverflow中文版 ways of validating an email address.

This is the code I have so far: (Don't worry I already know it's pretty pathetic.... )

public static void checkEmail()
{
    validEmail(emailAddresses);
    if(validEmail(emailAddresses))
    {

    }
}

public static boolean validEmail(String email) {
    return email.matches("[A-Z0-9._%+-][A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{3}");
}


The javax.mail package provides a class just for this: InternetAddress. Use this constructor which allows you to enforce RFC822 compliance.


Not perfect, but gets the job done.

static boolean validEmail(String email) {
    // editing to make requirements listed
    // return email.matches("[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}");
    return email.matches("[A-Z0-9._%+-][A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{3}");
}

void checkEmails() {
    for(String email : emailAddresses) {
        if(validEmail(email)) {
             // it's a good email - do something good with it
        }
        else {
             // it's a bad email - do something... bad to it? sounds dirty...
        }
    }
}


int indexOfAt = email.indexOf('@');
// first check : 
if (indexOfAt < 0) { 
  // error
}

// second check :
if (indexOfAt < 2) {
  // error
}

// third check :
int indexOfLastDot = email.lastIndexOf('.');
if (indexOfLastDot < indexOfAt || indexOfLastDot != (email.length() - 4)) {
  // error
}

Read http://download.oracle.com/javase/6/docs/api/java/lang/String.html for the documentation of the String methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜