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

code for email validation emailRegex in apex

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 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

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:



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  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:
		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;	

Thanks Erik!