function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sanjusfdcsanjusfdc 

code for email validation emailRegex in apex

Hi
I have tried below code for email validation:

String emailRegex = '^[a-zA-Z0-9_|\\\\#~`=?$^!{}+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,4}$';

valid email is like sanju.test@test.com should be accetable.
how to write code for below condition
1. Number of characters before @ should be equal or less than 64 characters
2. Below character should NOT be acceptable.
".@"
"@."
3. First and Last character should NOT be "."

Thank you in advance
GauravGargGauravGarg

Hi Sanju,

Salesforce provide email data-type field, which itself have email regex functionality. 

Still if you need custom regex please go through this link: https://help.salesforce.com/articleView?id=000170904&language=en_US&type=1

Thanks,

Gaurav
 

Erik M.Erik M.
There is no perfect regex expression for matching an email address since there is no formal definition of what constitutes a valid email address.  There is an interesting discussion of the issue at http://www.regular-expressions.info/email.html.  I had the situation where an imported text field could contain an email address or other information.  I needed to separate the email addresses from the other information and put them in separate fields.  For such a task the following code did the trick.
public static Boolean emailAddressIsValid(String email) {
		if (String.isEmpty(email)) return true;
		Boolean isValid = true;
			
		// Regex source: http://www.regular-expressions.info/email.html
		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()) 
		    isValid = false;
		return isValid;	
	}

 
Loureiro@UPFLoureiro@UPF
Thanks Erik!