We will see how to validate and check whether the entered email ID is valid or not using Java programming. Here I am writing a simple Java code that 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.
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}");
}
}
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
No comments:
Post a Comment
If you have any doubts or questions, please let us know.