Drills › Automate with triggers
Require a Contact email domain
Automate with triggers · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A training org lets anyone be a Contact, but a work Email must come from one approved domain.
Use a field-level addError in a trigger handler to reject Contact emails outside @example.com, including look-alike domains.
What you will learn
addError stops one record from saving and shows your message. Call it on a field to show the message next to that field:
item.Phone.addError('Use a 10-digit phone number.');
For case-insensitive text checks, value.toLowerCase().endsWith('@example.com') normalizes the case first. endsWith(x) is true only when value finishes with x.
Gotcha. Check the whole ending, @example.com. endsWith('example.com') lets [email protected] through.
The task
Complete the validator so any Contact Email that is not blank must end with @example.com, in any letter case.
Examples:
[email protected]→ saves[email protected]or[email protected]→ errorEmail must use @example.com.- no Email, or only spaces → your validator lets it through
Requirements:
- Check every Contact in the list. The trigger calls you on insert and update.
- Skip Emails that are blank (null, empty or only spaces).
- Check that the Email ends with
@example.com, ignoring letter case. - For any other Email, call
item.Email.addError('Email must use @example.com.').
Starter code
public class AS_4752F6B3261E_EmailValidator {
public static void validate(List<Contact> contacts) {
for (Contact item : contacts) {
if (String.isBlank(item.Email)) {
continue;
}
}
}
}
When it passes
Only Emails ending in @example.com (any case) save. Look-alike domains get the exact error on the Email field, blank Emails pass, a bad update keeps the old value, and a mixed 200-record insert saves the good half.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Move Opportunity logic to a handler · Stop recursive Account updates ›