We will see how to validate and check whether entered email ID is valid or not using Java programming. Here I am writing a simple Java code which will validate the format of email using regular expression(regex).
- Declare a variable with email addresses of type String[] array.
- Write a for loop which will iterate every item(email addresses) from your array.
- Create a parameterized method with return type boolean which will accept your email address and check for valid or not.
- Method will match the format of your email with regex: [a-zA-Z0-9._-][a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4} and return true or false.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| package rashid.jorvee;
public class ValidEmailValidator {
public static void main(String[] args) {
String[] emailAddresses= {"sohal@shopoo.co","adyu+@sud.com","asg_sj-@asgd.co","rashid@do.in.com","rashid.ta@rasj.com","fdh%sdfkj_@dsj.cojn"};
for(String email : emailAddresses) {
if(validEmail(email)) {
System.out.println("Valid email address :" +email);
}
else {
System.out.println("Invalid email address :"+email);
}
}
}
static boolean validEmail(String email) {
return email.matches("[a-zA-Z0-9._-][a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}");
}
}
|
Output:
Valid email address :vsohal@shopoo.co
Invalid email address :adyu+@sud.com
Valid email address :asg_sj-@asgd.co
Valid email address :rashid@rasj.com
Valid email address :rashid.ta@rasj.com
Invalid email address :fdh%sdfkj_@dsj.cojn
Another regex to check the email with at least three characters before and after the @ symbol:: [a-zA-Z0-9._-]{3,}@[a-zA-Z0-9.-]{3,}\.[a-zA-Z]{2,4}
ReplyDelete