Java의 간단한 이메일 유효성 검사

Java의 간단한 이메일 유효성 검사

2022-10-19 last update

23 minutes reading java tutorial webdev
이메일 유효성 검사는 이메일 주소의 품질과 정확성을 확인하는 데 중요합니다. 존재하지 않거나 비활성 상태이거나 잘못 입력된 이메일 계정을 유지하면 연락처 목록이 불필요하게 채워져 배달 가능성이 줄어들고 홍보 활동에 지장을 줄 수 있습니다.

유효한 이메일 주소는 로컬 부분, at 기호(@) 및 도메인 이름의 세 부분으로 구성됩니다. 이 형식을 따르지 않으면 주소가 유효하지 않게 됩니다.

대부분의 인터넷 메일 시스템 사양에 따라 로컬 부분은 다음 ASCII 표준 문자를 사용할 수 있습니다.
  • 자리 - 0~9
  • 소문자 및 대문자 라틴 문자 - a ~ z 및 A ~ Z
  • 인쇄 가능한 문자—!#$%&'*+-/=?^_`{|}~
  • dot—., 첫 문자나 마지막 문자가 아니거나 연속적으로 사용되지 않는 한

  • 또한 이메일 주소의 도메인 이름 섹션은 다음 문자로 구성될 수 있습니다.
  • 자리 - 0~9
  • 소문자 및 대문자 라틴 문자 - a ~ z 및 A ~ Z
  • 하이픈 또는 점 — – 또는 . , 초기 또는 마지막 문자가 아닌 한

  • 다음은 유효한 이메일 주소의 몇 가지 예입니다.
  • [email protected]
  • [email protected]
  • [email protected]

  • 반면에 잘못된 이메일 주소의 몇 가지 예는 다음과 같습니다.
  • alice.example.com(@ 문자 없음)

  • [email protected](두 개의 연속된 점은 허용되지 않음)

  • [email protected](도메인은 점으로 시작할 수 없음)

  • Java의 간단한 이메일 유효성 검사



    Apache Commons Validator 패키지는 다양한 데이터 유효성 검사 작업을 수행하기 위한 빌딩 블록을 제공합니다. 특히 EmailValidator 클래스를 사용하면 이메일 주소를 쉽게 확인할 수 있습니다.

    프로젝트에서 사용하려면 here 에서 다운로드할 수 있습니다. 사용 가능한 지침 here 을 사용하여 Maven 종속성으로 포함할 수도 있습니다.

    다음은 Apache Commons Validator를 사용하여 Java에서 간단한 이메일 유효성 검사를 수행하는 코드 예제입니다.
    `
    import java.util.ArrayList;
    import java.util.List;
    import org.apache.commons.validator.routines.EmailValidator;

    public class EmailValidation {
    public static boolean isValidEmail(String email) {
    // create the EmailValidator instance
    EmailValidator validator = EmailValidator.getInstance();

       // check for valid email addresses using isValid method
       return validator.isValid(email);
    

    }

    public static void main(String[] args) {
    List emails = new ArrayList();
    // valid email addresses
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("[email protected]");
    //invalid email addresses
    emails.add("alice.example.com");
    emails.add("[email protected]");
    emails.add("[email protected]");

       for (String value : emails) {
           System.out.println("The Email address " + value + " is " + (isValidEmail(value) ? "valid" : "invalid"));
       }
    

    }
    }
    `
    If we run the code, here is the output on the console:


    The Email address [email protected] is valid
    The Email address [email protected] is valid
    The Email address [email protected] is valid
    The Email address alice.example.com is invalid
    The Email address [email protected] is invalid
    The Email address [email protected] is invalid

    As you can see on the above output, the package has correctly validated whether the provided email addresses are valid or not.

    Java의 이메일 정규식

    If you want to have more control of the email validation process and verify a wide range of formats for email addresses, instead of the Apache Commons Validator package, you can use a regex string.

    A regular expression, commonly shortened to regex, allows you to create patterns for searching and matching strings of text. With regex, you can accurately check if the provided email addresses are in the required syntax.

    For example, here is a simple regex that only checks for the ‘@’ in an email address—the other conditions for a valid email address will not be checked; and there can be any number of characters before and after the sign.


    ^(.+)@(.+)$

    Let’s see how it can be implemented in a Java program:

    `
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class EmailValidation {
    private static final String regex = "^(.+)@(.+)$";

    public static void main(String args[]) {
    List emails = new ArrayList();
    // valid email addresses
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("alice#@example.me.org");
    //invalid email addresses
    emails.add("alice.example.com");
    emails.add("alice#example.com");
    emails.add("@example.me.org");

       //initialize the Pattern object
       Pattern pattern = Pattern.compile(regex);
    
       //searching for occurrences of regex
       for (String value : emails) {
           Matcher matcher = pattern.matcher(value);
    
           System.out.println("The Email address " + value + " is " + (matcher.matches() ? "valid" : "invalid"));
       }
    

    }
    }
    `

    Here’s the output on the console:


    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email alice.example.com is invalid
    Email alice#example.com is invalid
    Email @example.me.org is invalid

    Notice that we used the java.util.regex.Pattern class to create a Pattern object, which is a compiled representation of the regex. Then, we used the java.util.regex.Matcher class to interpret the Pattern and carry out match operations against the string of email addresses.

    로컬 부분 및 도메인 부분에 제한 추가

    Now, let’s enhance the previous regular expression in Java for email to include some restrictions for the local part and the domain part.

    Here are the restrictions we want to apply:

    • A-Z characters are permitted
    • a-z characters are permitted
    • 0-9 digits are permitted
    • Underscore(_), dash(-), and dot(.) are permitted
    • Other characters are not permitted

    Here is the regular expression:


    ^[A-Za-z0-9+_.-][email protected][A-Za-z0-9.-]+$

    Let’s check if string is email Java using the above regex:

    `
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class EmailValidation {
    private static final String regex = "^[A-Za-z0-9+_.-][email protected][A-Za-z0-9.-]+$";

    public static void main(String args[]) {
    //adding emails to an array list
    List emails = new ArrayList();
    // valid email addresses
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("[email protected]");
    //invalid email addresses
    emails.add("@example.com");
    emails.add("alice&example.com");
    emails.add("alice#@example.me.org");

       //initialize the Pattern object
       Pattern pattern = Pattern.compile(regex);
    
       //searching for occurrences of regex
       for (String value : emails) {
           Matcher matcher = pattern.matcher(value);
    
           System.out.println("Email " + value + " is " + (matcher.matches() ? "valid" : "invalid"));
       }
    

    }
    }
    `
    Here is the output:


    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email @example.com is invalid
    Email alice&example.com is invalid
    Email alice#@example.me.org is invalid

    로컬 부분의 모든 유효한 문자 확인

    Let’s expand the previous regular expression to permit a wider variety of characters in the local part of an email address. Most of the characters included in this check are rarely used and some email systems may not handle them. Furthermore, some of these characters, such as the single quote (‘), can pose a security risk to your application, especially if you do not sanitize user inputs properly.

    Here is the regular expression in Java for email validation:


    ^[a-zA-Z0-9_!#$%&'*+/=?
    {|}~^.-][email protected][a-zA-Z0-9.-]+$
    `

    Let’s use it to check for the validity of some email addresses:

    `
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class EmailValidation {
    private static final String regex = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-][email protected][a-zA-Z0-9.-]+$";

    public static void main(String args[]) {
    //adding emails to an array list
    List emails = new ArrayList();
    //valid email addresses
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("alice?[email protected]");
    emails.add("alice`[email protected]");
    emails.add("alice|[email protected]");
    //invalid email addresses
    emails.add("@example.com");
    emails.add("aliceexample.com");

       //initialize the Pattern object
       Pattern pattern = Pattern.compile(regex);
    
       //searching for occurrences of regex
       for (String value : emails) {
           Matcher matcher = pattern.matcher(value);
    
           System.out.println("Email " + value + " is " + (matcher.matches() ? "valid" : "invalid"));
       }
    

    }
    }
    `

    Here is the output:


    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email alice
    [email protected]이 유효하다
    앨리스에게 이메일 보내기| [email protected]이 유효합니다
    이메일 @example.com이 잘못되었습니다.
    이메일 aliceexample.com이 잘못되었습니다.
    `
    Try Mailtrap Email API here

    연속, 후행 또는 선행 점 확인

    Let’s continue improving our previous regular expressions to allow both the local part and the domain name part to have at least one dot. However, we’ll not allow any two consecutive dots or those dots appearing as the initial (or final) characters in the local part and domain part of the email address.

    Here is the regular expression:


    ^[a-zA-Z0-9_!#$%&'*+/=?
    {|}~^-]+(?:\.[a-zA-Z0-9_!#$%&'+/=?`{|}~^-]+↵\n"+
    ")@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
    `

    Here is its implementation in a Java program:

    `
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class EmailValidation {
    private static final String regex = "^[a-zA-Z0-9_!#$%&'+/=?`{|}~^-]+(?:\.[a-zA-Z0-9_!#$%&'+/=?`{|}~^-]+↵\n" +
    ")@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)$";

    public static void main(String args[]) {
    //adding emails to an array list
    List emails = new ArrayList();
    //valid email addresses
    emails.add("[email protected]");
    emails.add("alice#[email protected]");
    emails.add("alice`[email protected]");
    //invalid email addresses
    emails.add("@example.com");
    emails.add("[email protected].");
    emails.add("[email protected]");

       //initialize the Pattern object
       Pattern pattern = Pattern.compile(regex);
    
       //searching for occurrences of regex
       for (String value : emails) {
           Matcher matcher = pattern.matcher(value);
    
           System.out.println("Email " + value + " is " + (matcher.matches() ? "valid" : "invalid"));
       }
    

    }
    }
    `

    Here is the output:


    Email [email protected] is valid
    Email alice#[email protected] is valid
    Email alice
    [email protected]이 유효하다
    이메일 @example.com이 잘못되었습니다.
    이메일 [email protected] . 유효하지 않다
    이메일 [email protected]이 잘못되었습니다.
    `

    도메인 이름 부분에 제한 추가

    Finally, let’s improve the previous regex versions to ensure that the domain name part contains at least a single dot. Also, let’s add a condition that verifies that the section of the domain name after the final dot only comprises of letters. Furthermore, we’ll ensure that the top-level domain (such as .com) comprises of at least two to six letters.

    Here is the regular expression:


    ^[\\w!#$%&'*+/=?
    {|}~^-]+(?:\.[\w!#$%&'+/=?`{|}~^-]+)@(?:[a-zA-Z0- 9-]+\.)+[a-zA-Z]{2,6}$
    '

    Here is the Java program to check valid email address:

    `
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class EmailValidation {
    private static final String regex = "^[\w!#$%&'+/=?`{|}~^-]+(?:\.[\w!#$%&'+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$";

    public static void main(String args[]) {
    //adding emails to an array list
    List emails = new ArrayList();
    //valid email addresses
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("[email protected]");
    emails.add("[email protected]");
    //invalid email addresses
    emails.add("[email protected]");
    emails.add("[email protected].");
    emails.add("[email protected]");
    emails.add("[email protected]");

       //initialize the Pattern object
       Pattern pattern = Pattern.compile(regex);
    
       //searching for occurrences of regex
       for (String value : emails) {
           Matcher matcher = pattern.matcher(value);
    
           System.out.println("Email " + value + " is " + (matcher.matches() ? "valid" : "invalid"));
       }
    

    }
    }
    `

    Here is the output:


    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is valid
    Email [email protected] is invalid
    Email [email protected] is invalid
    Email [email protected] is invalid
    Email [email protected] is invalid
    50106

    OWASP 유효성 검사 정규식 사용

    Besides creating your own regular expression in Java for email verification, you can also use the ones that are freely provided by the OWASP organization.

    Here is an example of an OWASP validation regex:


    ^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$

    Let’s use it to check if string is email Java:

    `
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;