目录
How does email Validation work in Java?
Examples of Java Email Validation
1. Regex to validate the email with ‘@’ in between
2. Adding the restriction on the Username part of the email address
3. Restricting email from the dots whether leading, consecutive, or trailing
4. Restriction on the number of characters in the domain name
Conclusion
首页 Java java教程 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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1653
14
CakePHP 教程
1413
52
Laravel 教程
1304
25
PHP教程
1251
29
C# 教程
1224
24
突破或从Java 8流返回? 突破或从Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP与Python:了解差异 PHP与Python:了解差异 Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP与其他语言:比较 PHP与其他语言:比较 Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP与Python:核心功能 PHP与Python:核心功能 Apr 13, 2025 am 12:16 AM

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

Java程序查找胶囊的体积 Java程序查找胶囊的体积 Feb 07, 2025 am 11:37 AM

胶囊是一种三维几何图形,由一个圆柱体和两端各一个半球体组成。胶囊的体积可以通过将圆柱体的体积和两端半球体的体积相加来计算。本教程将讨论如何使用不同的方法在Java中计算给定胶囊的体积。 胶囊体积公式 胶囊体积的公式如下: 胶囊体积 = 圆柱体体积 两个半球体体积 其中, r: 半球体的半径。 h: 圆柱体的高度(不包括半球体)。 例子 1 输入 半径 = 5 单位 高度 = 10 单位 输出 体积 = 1570.8 立方单位 解释 使用公式计算体积: 体积 = π × r2 × h (4

PHP:许多网站的基础 PHP:许多网站的基础 Apr 13, 2025 am 12:07 AM

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

PHP的影响:网络开发及以后 PHP的影响:网络开发及以后 Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles