不使用正则表达式的 Java 电子邮件验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30415594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:05:22  来源:igfitidea点击:

Email validation in Java without using regular expression

javaemail-validation

提问by mindfreak

I understand that validating email with Regexwould have just been a matter of 3-4 lines of code. However, I'm looking to validate email without usingRegex.To an extent, the code successfully passes almost all the validations, however, still unable to figure out - how special characters can be avoided being the first & last character of the email address.

我知道使用Regex验证电子邮件只需 3-4 行代码。但是,我希望验证电子邮件在某种程度上,代码成功地通过了几乎所有的验证,但是,仍然无法弄清楚 - 如何避免特殊字符成为电子邮件地址的第一个和最后一个字符。without usingRegex.

List of specialChars ={'!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '/', '~', '[', ']'} ;

specialChars 列表 ={'!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '/', '~', '[', ']'} ;

What I am looking at is:

我在看的是:

If the username section (abc.xyz@gmail.com) starts or ends with any of the special characters, it should trigger an "Invalid email address" error.The same goes with domain section as well.

如果用户名部分 ( abc.xyz@gmail.com) 以任何特殊字符开头或结尾,则应触发“电子邮件地址无效”错误。域部分也是如此。

For eg...the following list of email-IDsshould print an "Invalid email ID"error message

例如...以下电子邮件 ID列表应打印“无效电子邮件 ID”error message

#[email protected]

abc.xyz&@gmail.com

abc.xyz&@!gmail.com

abc.xyz&@gmail.com!

#[email protected]

abc.xyz&@gmail.com

abc.xyz&@!gmail.com

abc.xyz&@gmail.com!

import java.util.Scanner;

public class Email_Validation {

    public static void main(String[] args) {

        // User-input code
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your email address");
        String email = scan.next();

        // Code to check if email ends with '.' (period sign) 
        boolean checkEndDot  = false;
        checkEndDot = email.endsWith(".");

        // Code to find out last index of '@' sign
        int indexOfAt = email.indexOf('@');
        int lastIndexOfAt = email.lastIndexOf('.');


        //Code to check occurence of @ in the email address  
        int countOfAt = 0;

        for (int i = 0; i < email.length(); i++) {
            if(email.charAt(i)=='@')
                countOfAt++; }


        // Code to check occurence of [period sign i..e, "."] after @ 
        String buffering = email.substring(email.indexOf('@')+1, email.length());
        int len = buffering.length();

        int countOfDotAfterAt = 0;
        for (int i=0; i < len; i++) {
            if(buffering.charAt(i)=='.')
                countOfDotAfterAt++; }


// Code to print userName & domainName
            String userName = email.substring(0, email.indexOf('@'));
            String domainName = email.substring(email.indexOf('@')+1, email.length());

                System.out.println("\n");   

               if ((countOfAt==1) && (userName.endsWith(".")==false)  && (countOfDotAfterAt ==1) &&   
                  ((indexOfAt+3) <= (lastIndexOfAt) && !checkEndDot)) {

                   System.out.println("\"Valid email address\"");}

               else {       
                        System.out.println("\n\"Invalid email address\""); }


                System.out.println("\n");
                System.out.println("User name: " +userName+ "\n" + "Domain name: " +domainName);


    }
}

How do I get this resolved ?

我如何解决这个问题?

回答by kg_sYy

How about this:

这个怎么样:

public class EmailMe {
  private static Set<Character> bad = new HashSet<>();

  public static void main(String[] args) {
    char[] specialChars = new char[] {'!', '#', '$', '%', '^', '&', '*', '(', ')', '-', '/', '~', '[', ']'} ;
    for (char c : specialChars) {
      bad.add(c);
    }
    check("#[email protected]");
    check("abc.xyz&@gmail.com");
    check("abc.xyz&@!gmail.com");
    check("abc.xyz&@gmail.com!");
  }

  public static void check(String email) {
    String name = email.substring(0, email.indexOf('@'));
    String domain = email.substring(email.indexOf('@')+1, email.length());
//    String[] split = email.split("@");
    checkAgain(name);
    checkAgain(domain);
  }


  public static void checkAgain(String part) {
    if (bad.contains(part.charAt(0))) System.out.println("bad start:"+part);
    if (bad.contains(part.charAt(part.length()-1))) System.out.println("bad end:"+part);
  }
}

回答by George Siggouroglou

I use EmailValidatorfrom the Apache Commons library.
An example above,

我使用Apache Commons 库中的EmailValidator
上面的一个例子,

String email = "[email protected]";
EmailValidator validator = EmailValidator.getInstance();
if (!validator.isValid(email)) {
   // The email is not valid.
}

or

或者

if (!EmailValidator.getInstance().isValid("[email protected]")) {
   // The email is not valid.
}

If you are using maven then you can use this dependency,

如果您使用的是 maven,则可以使用此依赖项

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.4.0</version>
    <type>jar</type>
</dependency>

回答by Dean J

So, take a look at the String API. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

所以,看看String API。 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Specifically, you've got String.length(), and String.charAt(). So you can get the first and last characters from the String very, very easily. You do this in your code at one point already; assuming you've got it.

具体来说,您有 String.length() 和 String.charAt()。因此,您可以非常非常轻松地从 String 中获取第一个和最后一个字符。你已经在你的代码中做到了这一点;假设你已经得到了。

You could run through a long if statement here;

你可以在这里运行一个很长的 if 语句;

char first = email.charAt(0);
if (first == '!' || first == '#' || <more here>) { 
    return false;
}

But that could be a headache. Another way to do this would be to use a Set, which is more efficient if you need to check this many times. (Lookup into a HashSet is generally pretty quick.) You'd create the set once, then be able to use it many times with Set.contains(first), for example.

但这可能会让人头疼。另一种方法是使用 Set,如果您需要多次检查,则效率更高。(查找 HashSet 通常非常快。)例如,您只需创建一次集合,然后就可以通过 Set.contains(first) 多次使用它。