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
mayara miranda 5mayara miranda 5 

I need to create a method via apex to validate if the email is valid

i'm having several problems with invalid emails on my org, i don't want to create validation rule. I want to create a method to check if the email is with the wrong syntax.

I'll leave some examples of the email I'm having problems.
 
frederico10@gmail.com31
elizandra@hotmail.com08
wermup@gmail.com968
jeanmiranda@hotmail.com.r


the end of the emails are invalid, usually the BR is missing or it has numbers after the .com.br

 
AbhinavAbhinav (Salesforce Developers) 
Hi Mayara,

Have you checked below link post?

https://developer.salesforce.com/forums/?id=906F000000092GXIAY
String email ='wermup@gmail.com968';
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;
	System.debug('--->'+res);

If it helps mark it as best answer.
 
vaani krvaani kr
Hi Mayara,

Please check below code

trigger TeacheEmailTrigger on Teacher__c (before insert, before update) {
 Set<String> emailvalid = new Set<String>();
    for(Teacher__c tech : Trigger.new){
        //clear them out, in the case of an update
        if(tech.Teacher_Email__c!=null){
            emailvalid.add(tech.Teacher_Email__c);
        } 
    }
    if(emailvalid.size()>0){
        EmailTriggerHelper.validateEmail(emailvalid);  
    }
}

public class EmailTriggerHelper {
   public static void validateEmail(Set<String> emailvalid){
    String emailRegex = '([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})';
    Pattern MyPattern = Pattern.compile(emailRegex);
        for(integer i=0 ; i<emailvalid.size() ; i++){
                Matcher MyMatcher = MyPattern.matcher(emailvalid.get(i));    
                if(!MyMatcher.matches()){
                     system.debug('Please Enter valid Email');               }
        }
    }
}

Method By using Triggers 
hope it will help you

Share your thoughts!

Thanks,
Vaani