# Require Contact Last Name

**Type:** Apex trigger · **Difficulty:** Easy · **Object:** Contact · **Topics:** Contact, Validation

Practice this problem interactively (write and run your Apex trigger against realistic data): https://www.forcechallenges.com/problems/require-contact-last-name

## Problem

**Scenario**
Sales reps often create Contacts quickly from the mobile app and sometimes leave the Last Name empty or type only spaces. Contacts without a last name cannot be searched, merged or used in email campaigns, so the data-quality team wants the save to be blocked with a clear message.

**Task**
Write a trigger handler on `Contact` that, **before** a Contact is inserted or updated:
1. Checks the `LastName` of every Contact in the batch.
2. Treats a missing value, an empty string and a value made only of spaces as blank.
3. Blocks each blank Contact by adding the error message `Enter a last name for this contact.` to that record, using `addError`.
4. Leaves valid Contacts alone, so in a mixed batch only the blank ones fail.

**Expected behavior**
- Inserting two Contacts, one with an empty `LastName` and one with `Valid`, produces exactly **one** error. The message mentions the last name.
- Inserting a Contact whose `LastName` is only spaces also produces an error.
- Inserting Contacts that all have a last name produces **no** errors.

**Example**
A batch of three Contacts: `LastName` = empty, `LastName` = three spaces, `LastName` = Smith.
- The first and second Contacts each receive the error `Enter a last name for this contact.`
- The third Contact is saved normally.
- The batch therefore reports 2 errors.

## Constraints

Write the logic for the before insert and before update events. Process every record in Trigger.new (the batch can hold many Contacts). Do not run SOQL or DML in this trigger; the check only needs the Contact's own field.

---
Source: ForceChallenges · last updated 2026-10-24
