Sub topic 3
Validating Formats with REGEX
Assume you know Salesforce objects, fields, records, and basic formulas. A validation rule blocks a save when its formula evaluates to TRUE.
Validating formats with REGEX
REGEX checks whether text matches a pattern. Combine it with ISBLANK when blank values are allowed.
AND(
BillingCountry = "USA",
NOT(ISBLANK(BillingPostalCode)),
NOT(REGEX(BillingPostalCode, "[0-9]{5}(-[0-9]{4})?"))
)This rule rejects a US postal code unless it has five digits or the ZIP+4 format. The pattern uses [0-9] for a digit and ? to make the four-digit suffix optional.
Referencing related records and global variables
A validation rule can read fields from a parent record through a relationship, such as Account.Industry. It can also use global variables:
AND(
Account.Industry = "Technology",
$User.Department = "Sales",
ISBLANK(Website)
)This blocks a blank Website only for users in Sales when the Account is in Technology. A rule can read parent fields, but it cannot directly validate all child records from the parent.
Scoping and bypassing rules
Use $RecordType.DeveloperName, $Profile.Name, or $User.Id to limit a rule. Prefer stable developer names or custom permissions over profile names, which can change.
Create a custom permission named Bypass_Validation_Rules, assign it through a permission set, and add this condition:
AND(
NOT($Permission.Bypass_Validation_Rules),
ISPICKVAL(StageName, "Negotiation/Review"),
OR(ISBLANK(Amount), Amount <= 0)
)The rule applies unless the current user has that permission.
Save order and alternatives
Validation rules run during the save process after before-save automation and before the record commits. If a rule returns TRUE, Salesforce stops the save and displays the configured field-level or page-level error.
Use a validation rule for a formula-based restriction. Use a Flow for guided automation, updates, or more readable branching. Use Apex for complex calculations, multiple-record operations, or transaction-specific behavior.
Testing and troubleshooting
Test both rejected and accepted records. Apex can assert the validation failure:
@IsTest
private class OpportunityValidationTest {
@IsTest
static void rejectsMissingAmountInNegotiation() {
Opportunity opp = new Opportunity(
Name = 'Test Opp',
StageName = 'Negotiation/Review',
CloseDate = Date.today().addDays(30)
);
Database.SaveResult result = Database.insert(opp, false);
System.assert(!result.isSuccess());
System.assertEquals(
StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION,
result.getErrors()[0].getStatusCode()
);
}
}If deployment fails, check field permissions, record type values, formula references, and test data. Deploy to a sandbox first. Confirm that integration users have only the intended bypass permission.
Exercise
What happens when a validation rule formula evaluates to FALSE?
Show answer
The rule does not block the save.