+ Start a Discussion
shiva pendemshiva pendem 

Email validation in Apex Controller

HI Friends,

Can any one suggest me how to write Email Validation in apex controller. Here i am using one Regular expression to validate the Email in my controller method but its not working as per my senario
Using this Code in IF : if(Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z-]+.[a-zA-Z.]{2,4}',cust_conemail)){

But its allows in all senarios but the thing is after @ need to accept only one or none hyphen but now its allowing more than one hyphens.
want this format : shiva.pendem@stead-fast.com //working fine
the issue is : shiva.pendem@stead--fast.com i want to restrict this format (More than one Hyphen). // need to restrict this
i.e only one or none hyphen want to allow.

please suggest me.

if (pattern.matches('^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-\\]+)*@' + '[A-Za-z0-9-\\]+(\\.[A-Za-z0-9-\\]+)*(\\.[A-Za-z]{2,})$',cust_conemail)){
Vijay NagarathinamVijay Nagarathinam

Use the following code, it will work.
public static Boolean validateEmail(String email) {
	Boolean res = true;	
String emailRegex = '^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
	Pattern MyPattern = Pattern.compile(emailRegex);
	Matcher MyMatcher = MyPattern.matcher(email);

	if (!MyMatcher.matches()) 
	    res = false;
	return res;