Tuesday, 29 March 2011

Email validation using Regular Expression

See the following example :-


import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 *
 * @author Prasobh.K
 */
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);
        String email = "meprasobh@yahoo.com";
        checkMyEmailValidity(email);
    }


    /**
     * Validate val with regular expression
     * @param val val for validation
     * @return true valid val, false invalid val
     */
    private boolean validate(final String val) {


        matcher = pattern.matcher(val);
        return matcher.matches();


    }


    public static void main(String[] args) {
        new EmailValidator();
    }


    private void checkMyEmailValidity(String email) {
        if (validate(email)) {
            System.out.println("your have a valid email id ");
        } else {
            System.out.println("Invalid email id");
        }


    }
}

No comments:

Post a Comment