Sunday 28 September 2014

Validating Email Address Using Regular Expressions In Java


Few days back working on some project, i come across some issue to validate just email in between complete project and email was needed to be validate at multiple places in the code so i thought to write a class like a wrapper Email Validator so that we can use at at any instance. so let me share that email Validator class with you guys. So the important thing that i have used is that i have used regular expression to validate email address. The Email Validator Class is given below.
//Email Validator Class
package EmailValidate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
*
* @param hex
* hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
As we have wrote wrapper class above now the question arise that how we are going use it as validator of email address.
Validating Email in a JtextField
Emailvalidator emailValidator = new Emailvalidator();
if(!emailValidator.validate(emailField.getText().trim())) {
System.out.print("Invalid Email ID");
/*
Perform any action here that you want to show while email address is invalid 
i-e change the color of the field */
}
Validating Email in Console
I will show this part writing a small program which will ask for email id in console, If the email Id is valid it will print Valid Email else it will print Invalid Email ID. So let's move on with the code
package EmailValidate;
import java.util.Scanner;
public class VEmail {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Enter email address :");
String EmText = input.next();
EmailValidator emailValidator = new EmailValidator();
if(!emailValidator.validate(EmText.trim())) {
System.out.print("Invalid Email ID");
}
else
{
System.out.print("Valid Email ID");
}
}
}
So that's all for Using Email Validator for multiple purposes by writing a general class.

0 comments:

Post a Comment