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
Afzaal HassanAfzaal Hassan 

How to check if an email contains the right format

I had a simple question. I want to check if an email entered in the form is the right format. How do you splice in apex? In other words I want to see that after the @ symbol, we only have gmail.com. I was going to write something like 
if(email__c.contains('@gmail.com'){} but then I realized that this may not be enough because someone could potentially enter an email of gmail.com@hotmail.com for example. So I want to see what I can write in apex to check if the email is in the format ###@gmail.com
Thank you
Best Answer chosen by Afzaal Hassan
Greg HGreg H
Use the split method to create a list of strings using the @ as the break point. Then grab the second string in the list and compare.
-greg
List<String> emailParts = new List<String>(); //list for holding email parts
emailParts = EMAILSTRING.split('@'); //create a list from the email address based upon breaking at the occurance of @
String domain = emailParts[1]; //grab the second element from the list as the domain

 

All Answers

Greg HGreg H
Use the split method to create a list of strings using the @ as the break point. Then grab the second string in the list and compare.
-greg
List<String> emailParts = new List<String>(); //list for holding email parts
emailParts = EMAILSTRING.split('@'); //create a list from the email address based upon breaking at the occurance of @
String domain = emailParts[1]; //grab the second element from the list as the domain

 
This was selected as the best answer
Afzaal HassanAfzaal Hassan
@Greg H. Thanks for the response. So I was actually writing a custom exception which is why I was testing for this. This apex class is being called by a Flow that I created. So when inserting the contact, if the email is not in the format @gmail.com, then it should throw a custom error message. How would we write a catch statment for something like that?

public class LPP_ContactInsertOnboarding {
    @InvocableMethod(label='Insert Contacts' description='creates new contact record for the flow.')
    public static List<String> insertContacts(List<Contact> conLst){
        List<String> contactMsg = new List<String>();
        try{
            insert conLst;
            //contactMsg.add('Contact record for ' + conLst[0].FirstName + conLst[0].LastName + 'has been created. Click Next for User setup.');
            contactMsg.add(conLst[0].id);
        }catch(Exception e){
            contactMsg.add('Error in creating contact record. The reason is because: ' + e.getMessage() + 'Please hit the Next button to go back to the form and enter this missing field.');
        }// WILL NEED ANOTHER CATCH STATEMENT?
        system.debug(contactMsg);
        return contactMsg;
    }
}