Java의 간단한 이메일 유효성 검사
유효한 이메일 주소는 로컬 부분, at 기호(@) 및 도메인 이름의 세 부분으로 구성됩니다. 이 형식을 따르지 않으면 주소가 유효하지 않게 됩니다.
대부분의 인터넷 메일 시스템의 사양에 따라 로컬 부분은 다음 ASCII 표준 문자를 사용할 수 있습니다.
또한 이메일 주소의 도메인 이름 섹션은 다음 문자로 구성될 수 있습니다.
다음은 유효한 이메일 주소의 몇 가지 예입니다.
반면에 유효하지 않은 이메일 주소의 예는 다음과 같습니다.
[email protected](점 2개 연속 불가)
[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+_.-]+@[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+_.-]+@[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_!#$%&'*+/=?
{|}~^.-]+@[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_!#$%&'*+/=?`{|}~^.-]+@[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
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;
public class EmailValidation {
private static final String regex = "^[a-zA-Z0-9_+&-]+(?:\.[a-zA-Z0-9_+&-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,7}$";
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]");
//invalid email addresses
emails.add("alice.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 [email protected] is valid
Email [email protected] is valid
Email alice.example.com is invalid
Email [email protected] is invalid
Email [email protected] is invalid
1045196 1045196
Reference
이 문제에 관하여(Java의 간단한 이메일 유효성 검사), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/sofiatarhonska/simple-email-validation-in-java-1leh텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)