찾다
Javajava지도 시간Java 이메일 검증

Java 이메일 검증

Aug 30, 2024 pm 04:21 PM
java

Java Email Validation is done to check the accuracy and quality of the email address that the user input. In Java, Email Validation is done with the help of regex expressions. In order to restrict the users to fill the database from the unnecessary email addresses and prevent the application to be used only by authentic users, email addresses play an important role. Almost all the websites and Apps use the email address of the user to sign up and validate them using their algorithms. So before designing the Sign-up Page or performing any task that requires an email address, it is important to validate those email addresses before proceeding further.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How does email Validation work in Java?

Let us understand the step by step procedure of validating an email in Java along with its implementation in the code:

1. In Java, we validate the email address with the help of the regex expressions.
2. Regular expression is not a language but it defines a pattern for a String through which we can search, compare, edit or manipulate a text. It does not change from language to language (though they are slightly different in some languages).
3. In Java, Regex class is present in the Java library named as java. util.regex
4. In Java, there is a class with the name ‘Pattern’ whose object is the compiled version of the regular expression. In order to create the pattern object, we use its method ‘compile’ (which is public static) and pass the regular expression in it.
5. ‘Matcher’ is a java regex engine object which matches the input string with the object of the Pattern class created above. Method ‘matcher’ takes the input string (email that needs to be checked) as an argument.
6. Method ‘matches’ is used that compares the input string with the regex expression and returns the boolean result based on the decision whether the input string matches with the mentioned regular expression or not.
7. Result is stored in a boolean variable and based on that, the respective message is printed on the console to the user.

We can implement as many restrictions in the validation code of email as we want to depend on the requirement of the application but the general restriction that should be there in the Email address of any user is given below:

  • Restriction on ‘@’ part of the email address.
  • Restriction on the dots (.) present in the email address whether leading, trailing, or consecutive.
  • Restriction on username part of the email address
  • Restriction on the no. of characters in the top-level domain name of the email address.

Examples of Java Email Validation

In this article, we would implement all the above-mentioned Validation restrictions and that too step by step to make you understand the code better.

1. Regex to validate the email with ‘@’ in between

There should be one ‘@’ sign present in the email address

import java.util.regex.*;
import java.util.*;
public class Main{
public static boolean isValid(String email)
{
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);
if (email == null)
return false;
return pattern.matcher(email).matches();
}
public static void main(String args[]){
String email = "[email protected]";
boolean result = isValid(email);
if (result == true)
System.out.println("Provided email address "+ email+ " is valid \n");
else
System.out.println("Provided email address "+ email+ " is invalid \n");
}
}

Output:

Java 이메일 검증

For the below line

address = 'yashi..goyalyahoo.com'

Output:

Java 이메일 검증

2. Adding the restriction on the Username part of the email address

  • All the capital alphabets [A- Z] are allowed.
  • All the small alphabets [a- z] are allowed.
  • All the numbers [0- 9] are allowed.
  • Email can address can contain dot (.), underscore ( _ ), dash ( – ) in the username.
  • Other special characters are not allowed.
import java.util.regex.*;
import java.util.*;
public class Main{
public static boolean isValid(String email)
{
String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
Pattern pattern = Pattern.compile(regex);
if (email == null)
return false;
return pattern.matcher(email).matches();
}
public static void main(String args[]){
String email = "yashi + [email protected]";
boolean result = isValid(email);
if (result == true)
System.out.println("Provided email address "+ email+ " is valid \n");
else
System.out.println("Provided email address "+ email+ " is invalid \n");
}
}

Output:

Java 이메일 검증

For the below line

address = '[email protected]'

Output:

Java 이메일 검증

3. Restricting email from the dots whether leading, consecutive, or trailing

  • More than one dot (.) can be present in the email address
  • Consecutive dots are not allowed in both the local and domain part.
  • No email is allowed to start or end with a dot.
import java.util.regex.*;
import java.util.*;
public class Main{
public static boolean isValid(String email)
{
String regex = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$";
Pattern pattern = Pattern.compile(regex);
if (email == null)
return false;
return pattern.matcher(email).matches();
}
public static void main(String args[]){
String email = "[email protected]";
boolean result = isValid(email);
if (result == true)
System.out.println("Provided email address "+ email+ " is valid \n");
else
System.out.println("Provided email address "+ email+ " is invalid \n");
}
}

Output:

Java 이메일 검증

For the below line

address = '[email protected]'

Output:

Java 이메일 검증

4. Restriction on the number of characters in the domain name

  • There should be at least one dot in the domain name.
  • In the domain name, after the dot, only the letters would continue.
  • Length of domain name should be between 2- 6 letters.
import java.util.regex.*;
import java.util.*;
public class Main{
public static boolean isValid(String email)
{
String regex = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[\\a-zA-Z]{2,6}";
Pattern pattern = Pattern.compile(regex);
if (email == null)
return false;
return pattern.matcher(email).matches();
}
public static void main(String args[]){
String email = "[email protected]";
boolean result = isValid(email);
if (result == true)
System.out.println("Provided email address "+ email+ " is valid \n");
else
System.out.println("Provided email address "+ email+ " is invalid \n");
}
}

Output:

Java 이메일 검증

For the below line

address = '[email protected]'

Output:

Java 이메일 검증

Conclusion

The above description clearly explains what email validation is and how it works in the Java program. Email validation is used widely as it can be a login id or unique username of every user to log in to the website. So it is important for a programmer to learn to validate it before using it for further process in the correct flow of code.

위 내용은 Java 이메일 검증의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?Mar 17, 2025 pm 05:46 PM

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:45 PM

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?Mar 17, 2025 pm 05:44 PM

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:43 PM

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Mar 17, 2025 pm 05:35 PM

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구