Sub topic 9
Validating formats with REGEX
This chapter covers the REGEX function in validation rule formulas. It assumes you can write an error condition formula (true means invalid), combine conditions with AND, OR, and NOT, and handle blank values with ISBLANK. You should also be comfortable with the Setup and Object Manager screens where rules are created.
What REGEX does in a formula
REGEX(text, regex_text) returns true when the whole text value matches a regular expression. A regular expression, or regex, is a compact pattern that describes which strings are allowed. Examples are "exactly five digits" or "letters followed by a dash and a number".
Two details shape every rule you write with it:
- The match is against the entire value.
REGEXbehaves as if the pattern were anchored at both ends.REGEX("12345-abc", "\\d{5}")is false, because the whole string is not five digits. You do not add^and$yourself. - Validation rules fire on invalid data.
REGEXreturns true for valid values, so you wrap it inNOTto flag bad ones.
Salesforce uses Java-style regex syntax. The most common building blocks are listed here.
| Pattern | Meaning | Column |
|---|---|---|
| `\d` | One digit. In a formula it must be written `\\d` (see below). | |
| `[A-Z]` | One uppercase letter. | |
| `[A-Za-z0-9]` | One letter or digit. | |
| `.` | Any one character. | |
| `{5}` | Exactly five of the previous item. | |
| `{2,4}` | Between two and four of the previous item. | |
| `+` | One or more of the previous item. | |
| `*` | Zero or more of the previous item. | |
| `?` | Zero or one of the previous item. | |
| `(a\ | b)` | Either `a` or `b`. |
| `\\.` | A literal dot. |
Escaping backslashes
Inside a formula string, a backslash is itself an escape character. To give the regex engine a single \, you type two: \\. That is why a digit is written \\d in the formula but is described as \d in regex documentation.
This is the most common source of broken REGEX rules. If you copy a pattern from a regex tester, double every backslash before pasting it into the formula editor.
Worked example: US postal codes
The Account rule below flags a US billing postal code that is not five digits or ZIP+4 (five digits, a hyphen, four digits).
AND(
BillingCountry = "USA",
NOT(ISBLANK(BillingPostalCode)),
NOT(REGEX(BillingPostalCode, "\\d{5}(-\\d{4})?"))
)Read it from the inside out:
REGEX(BillingPostalCode, "\\d{5}(-\\d{4})?")is true for94105and94105-1234. The group(-\\d{4})?makes the hyphen and four digits optional as a unit.NOT(...)turns that into "the code is malformed".NOT(ISBLANK(...))stops the rule from firing when the field is empty. Without it, an empty field fails the match and the rule blocks every Account with no postal code.BillingCountry = "USA"limits the check to US addresses, so German or Canadian codes are not rejected.
The country comparison depends on how your org stores country values. If your org uses state and country picklists, the stored value may be United States or US rather than USA. Check the real values before you rely on the comparison.
Why blank handling matters more with REGEX
An empty string does not match most patterns. A pattern such as \\d{5} is false for a blank field, so NOT(REGEX(...)) is true, and the rule blocks the save.
You have two choices, and they express different business rules:
- The field is optional. Add
NOT(ISBLANK(Field))to theAND, as in the postal code example. - The field is required. Leave the blank check out. The
REGEXfailure then also catches empty values, though a dedicated required-field rule with its own message is usually clearer for users.
Prefer a separate rule for "required" and one for "format". Each can then carry an error message that says exactly what is wrong.
A second example: product codes
Suppose a custom Product Code field must look like ABC-1234: three uppercase letters, a hyphen, then four digits.
AND(
NOT(ISBLANK(Product_Code__c)),
NOT(REGEX(Product_Code__c, "[A-Z]{3}-\\d{4}"))
)An error message such as "Product Code must be three capital letters, a hyphen, and four digits, for example ABC-1234." names the rule and gives an example. That message does more for the user than "Invalid product code".
Case sensitivity and optional flags
REGEX is case-sensitive. [A-Z]{3} rejects abc. To accept either case you have two options:
- Widen the character class:
[A-Za-z]{3}. - Normalize first:
REGEX(UPPER(Product_Code__c), "[A-Z]{3}-\\d{4}").
The second form checks the format but does not change the stored value. If the data must be stored in uppercase, a validation rule can only reject lowercase. Converting it needs a workflow-style update, a flow, or Apex.
Field types and the TEXT function
REGEX takes text. It works directly on Text, Email, Phone, URL, and Text Area fields. It does not accept Number, Currency, Date, or Picklist fields. For those, convert first:
- Picklist:
REGEX(TEXT(Region__c), "[A-Z]{2}"). - Number:
REGEX(TEXT(Employee_Id__c), "\\d{6}").
Be careful with TEXT on numbers. It drops formatting such as thousands separators and may drop trailing zeros after a decimal point, so a pattern designed around 007 will not match the number 7. If the value is really an identifier with leading zeros, store it as a Text field, not a Number field. A number field cannot hold leading zeros at all.
Phone numbers: be wary of strict patterns
Phone formats vary by country, and users paste values with spaces, brackets, and extensions. A rule that demands (###) ###-#### will block valid international numbers and annoy users who enter 415-555-0100.
Two sensible approaches:
- Accept a few common US layouts:
REGEX(Phone, "\\(?\\d{3}\\)?[- .]?\\d{3}[- .]?\\d{4}"). Here\\(?allows an optional opening bracket, and[- .]?allows an optional hyphen, space, or dot. - Strip formatting and test only the digit count:
LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Phone, "-", ""), " ", ""), "(", "")) .... This gets long quickly, so ask whether the rule is worth its maintenance cost.
For many orgs, restricting a strict phone rule to one country, in the same way as the postal code example, is the practical middle ground.
Common errors
- Single backslashes.
\dinstead of\\dcauses a save error or a pattern that never matches. - Forgetting that the match is anchored. A pattern for a prefix, such as
ABC, will not matchABC-1234. WriteABC.*or the full format. - Missing blank check. Optional fields block saves when empty.
- Using REGEX on unsupported types. Wrap Number or Picklist fields in
TEXT. - Overly strict patterns. Names, addresses, and international values rarely fit a tight pattern. Reject only what is clearly wrong.
- Overlong patterns. Formulas have a compiled size limit, and
REGEXhas its own limit on pattern complexity. If a rule hits either, simplify the pattern or move the check to a flow or Apex.
Testing the rule
Before you activate a regex rule, try at least these inputs by creating or editing records in a sandbox:
- A valid value, which must save.
- An invalid value, which must show your error message.
- A blank value, which must behave according to your decision on optional or required.
- A near miss, such as one digit too many, to confirm the anchoring.
The Apex testing chapter shows how to automate these checks.
Exercise
A custom Text field InvoiceNumber_c must look like INV- followed by exactly six digits, for example INV-004512. The field is optional. Write the error condition formula, and explain why each backslash is doubled.
Show answer
AND(NOT(ISBLANK(InvoiceNumberc)), NOT(REGEX(InvoiceNumber__c, "INV-\\d{6}"))). The blank check lets empty values save because the field is optional. REGEX returns true for valid values, so NOT flags bad ones, and the match covers the whole value, so INV-0045123 fails. Each backslash is doubled because the formula string treats a backslash as an escape character, so \\d reaches the regex engine as \d.
Exercise
A Number field EmployeeIdc must contain exactly six digits. A teammate writes NOT(REGEX(EmployeeId__c, "\\d{6}")) and the rule fails to save. What is wrong, and what are the limits of the fix?
Show answer
REGEX needs text, and a Number field is not text. Wrap it: NOT(REGEX(TEXT(EmployeeId_c), "\\d{6}")). TEXT drops leading zeros because a Number field cannot store them, so an ID like 004512 is stored as 4512 and fails. If IDs can start with zero, change the field to Text.