Searching...
Wednesday, 4 June 2014

Email validation using Java Regex

05:09

Pattern Details

Pattern =  ^[A-Z0-9._]+@[A-Z0-9]+\\.[A-Z]{2,6}$
Details:-
^= Start of the pattern
[A-Z0-9._]= First part of the email should contains only A-Z or 0-9 and . _
@[A-Z0-9-]= Second part of the email should contains only A-Z or 0-9 after @
\\.[A-Z]{2,6} = Third part should contains only A-Z values and minimum 2 maximum characters required.
&= End of the pattern
Example
package com.vinod.test;

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

/**
 *@authorvinod.kumaran
 *
 * This is a simple email validator program using Java Regular expression.
 *
 * Pattern Details- ^[A-Z0-9._]+@[A-Z0-9]+\\.[A-Z]{2,6}$
 *
 * ^ = Start of the pattern
 *
 * [A-Z0-9._]= First part of the email should contains only A-Z or 0-9 and . _
 *
 *@[A-Z0-9-]= Second part of the email should contains only A-Z or 0-9 after @
 *
 * \\.[A-Z]{2,6}= Third part should contains only A-Z values and minimum 2 maximum characters required.
 *
 * $ = End of the pattern
 *
 */
public class EmailValidator {

public static final Pattern EMAIL_REGEX = Pattern.compile("^[A-Z0-9._]+@[A-Z0-9-]+\\.[A-Z]{2,6}$",
Pattern.CASE_INSENSITIVE);

public static void main(String[] args) {
// Valid email id
System.out.println(validate("kkvinod@pretechsol.com"));

// Invalid email id (first part contains %)
System.out.println(validate("kkvin%od@pretechsol.com"));

// Invalid email id (Second part contains _)
System.out.println(validate("kkvinod@prete_chsol.com"));

// Invalid email id (Third part contains more than 6 characters)
System.out.println(validate("kkvinod@pretechsol.comcomcom"));

}

public static boolean validate(String emailAddress) {
Matcher matcher = EMAIL_REGEX.matcher(emailAddress);
return matcher.find();
}
}
Output
true
false
false
false

0 comments: