Using REGEX in Salesforce Validation Rules
Background
REGEX comes in extremely handy when it comes to enforcing your data format. Before diving into the use cases, let’s review some basic REGEX syntax used in our sample below.
- \\ escape character
The backslash characters (\) must be changed to double backslashes (\\) because the backslash is an escape character in Salesforce.
- [abc] matches a or b or c
- [a-z] matches any character between a to z
- {} matches the specified quantity of the previous token. {4} matches exactly 4 and {4,} matches 4 or more.
- + matches 1 or more of the preceding token.
Use Case 1: Validate Phone Number Format
Let’s say you want your phone number format to be (123)-456–7890. Your Validation Rule will look like this:
!REGEX(Phone, "\\([0-9]{3}\\)-[0-9]{3}-[0-9]{4}")
Let’s break it down:
- ! means not
- The formula looks at the Phone field
- \\( matches a “(“ character
- [0–9] matches any character from 0–9
- {3} matches 3 of the characters from [0–9]
- \\) matches a “)” character
- - Matches a “-” character
- [0–9] matches any character from 0–9
- {3} matches 3 of the characters from [0–9]
- - Matches a “-” character
- [0–9] matches any character from 0–9
- {4} matches 4 of the characters from [0–9]
Use Case 2: Validate Account Unique Identifier Format
Your company sells to partners and end customers. If an Account is a partner, its unique identifier format should be DEE-P-1234AB; If an Account is a customer, its unique identifier format should be DEE-C-1234AB.
!REGEX(Unique_Identifier__c, "DEE-[PC]-[0-9]{4}[A-Z]{2}")
Let’s break it down:
- ! means not
- The formula looks at the Unique_Identifier__c field
- DEE- matches “DEE-”
- [PC] matches a “P” or a “C”
- - Matches a “-” character
- [0–9] matches any character from 0 to 9
- {4} matches 4 of the characters from [0-9]
- [A-Z] matches any character from A to Z
- {2} matches 2 of the characters in [A-Z]
Use Case 3: Validate Email Format
Ready for a more complicated one? Let’s look at how we can use REGEX to validate email format!
!REGEX(Email, "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}")
Let’s break it down:
- ! means not
- The formula looks at the Email field
- [a-zA-Z0–9._%+-] matches any character from a to z, A to Z, 0 to 9, ”.”, “-”, “%”, ”+”, or “-”
- + looks for at least 1 of the character in [a-zA-Z0–9._%+-]
- @ looks for the “@” in email
- [a-zA-Z0–9.-] matches any character from a to z, A to Z, 0 to 9, ”.” or “-”
- + looks for at least 1 of the character in [a-zA-Z0–9.-]
- \\. matches a “.” character
- [a-zA-Z] matches any character from a to z or A to Z
- {2,} matches 2 or more of the characters in [a-zA-Z]
I hope that was helpful. Test it out in your sandbox! See you on the trails :)