Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package org.hibernate.validator.internal.constraintvalidators;
 
 import java.net.IDN;
 
import static java.util.regex.Pattern.CASE_INSENSITIVE;

Checks that a given character sequence (e.g. string) is a well-formed email address.

The specification of a valid email can be found in RFC 2822 and one can come up with a regular expression matching all valid email addresses as per specification. However, as this article discusses it is not necessarily practical to implement a 100% compliant email validator. This implementation is a trade-off trying to match most email while ignoring for example emails with double quotes or comments.

Author(s):
Emmanuel Bernard
Hardy Ferentschik
public class EmailValidator implements ConstraintValidator<EmailCharSequence> {
	private static String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
	private static String DOMAIN =  + "+(\\." +  + "+)*";
	private static String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";

Regular expression for the local part of an email address (everything before '@')
	private Pattern localPattern = java.util.regex.Pattern.compile(
			 + "+(\\." +  + "+)*"
	);

Regular expression for the domain part of an email address (everything after '@')
	private Pattern domainPattern = java.util.regex.Pattern.compile(
	);
	public void initialize(Email annotation) {
	}
	public boolean isValid(CharSequence valueConstraintValidatorContext context) {
		if ( value == null || value.length() == 0 ) {
			return true;
		}
		// split email at '@' and consider local and domain part separately
		String[] emailParts = value.toString().split"@" );
		if ( emailParts.length != 2 ) {
			return false;
		}
		// if we have a trailing dot in local or domain part we have an invalid email address.
		// the regular expression match would take care of this, but IDN.toASCII drops trailing the trailing '.'
		// (imo a bug in the implementation)
		if ( emailParts[0].endsWith"." ) || emailParts[1].endsWith"." ) ) {
			return false;
		}
		if ( !matchPartemailParts[0],  ) ) {
			return false;
		}
		return matchPartemailParts[1],  );
	}
	private boolean matchPart(String partPattern pattern) {
		try {
			part = IDN.toASCIIpart );
		}
		catch ( IllegalArgumentException e ) {
			// occurs when the label is too long (>63, even though it should probably be 64 - see http://www.rfc-editor.org/errata_search.php?rfc=3696,
			// practically that should not be a problem)
			return false;
		}
		Matcher matcher = pattern.matcherpart );
		return matcher.matches();
	}
New to GrepCode? Check out our FAQ X