Test regex in Salesforce validation rules

How the Salesforce REGEX function works in validation rules, how to test a pattern before it blocks users, and when a simpler check or field type is the better choice.

Salesforce validation rules can use the REGEX function to check that a text value follows a required pattern before a record saves. This review explains what the function checks, how to test a pattern before it reaches users, and when a regular expression is the wrong tool.

Is regex the right tool for your validation rule?

Use REGEX when a value has a fixed structure that would otherwise take a long chain of LEN, MID, BEGINS and ISNUMBER calls. Good examples are US ZIP codes, internal reference numbers and account codes with set prefixes. The main benefit is that one compact expression replaces many lines of formula logic. The main tradeoff is that a pattern is harder to read and maintain than plain formula functions. A small mistake can also block valid records, and users see an error that does not explain the pattern.

A simpler approach is better in three cases. First, when a standard field type already enforces the format, such as an Email field, which Salesforce checks for email syntax, or a Number field, which rejects non-numeric input. Second, when the check is only about length, a prefix or whether a value is present. Third, when valid values vary widely, as with personal names, international addresses or phone numbers from many countries. In that last case, a strict pattern will reject real data.

What REGEX actually does in a validation rule

REGEX(text, regex_text) returns TRUE when the text matches the pattern. It does not change stored data: no characters are replaced, reversed or reformatted. It only tests the value. A validation rule shows its error when the formula evaluates to TRUE, so the usual form wraps REGEX in NOT. The rule then fires when the value does not match.

  • Whole-string matching: Salesforce documentation describes REGEX as matching the entire string. The pattern \d{5} matches 12345 but not ZIP 12345. Adding ^ and $ is unnecessary, though harmless.
  • Java-based syntax: the regex syntax is documented as based on Java's. Constructs that behave a certain way in JavaScript or PCRE testers may behave differently or be rejected.
  • Double backslashes: the backslash is an escape character in formula strings, so a pattern written as \d in a tester must be entered as \d in the formula.
  • Text input only: REGEX works on text. Number, picklist and date values need converting with TEXT() first.
  • Blank values: an empty field will not match a pattern that requires characters, so NOT(REGEX(...)) fires on blank values. If the field is optional, add an ISBLANK check.
AND(
  NOT(ISBLANK(BillingPostalCode)),
  NOT(REGEX(BillingPostalCode, "\\d{5}(-\\d{4})?"))
)

This example accepts a five-digit US ZIP code with an optional four-digit extension. It skips the check when the field is blank. Each \d in the formula becomes \d once Salesforce processes the string escape.

How to test a pattern before it goes live

Online regex testers are useful for drafting. However, many default to JavaScript or PCRE behavior and report a match anywhere inside the string. A pattern that looks correct in a tester can still fail in Salesforce, so close those gaps on purpose.

  • 1. Draft the pattern in a tester set to Java syntax if it offers that option. Wrap the pattern in ^ and $ while testing to imitate whole-string matching.
  • 2. Write a list of values that should pass and values that should fail. Include blank values, leading and trailing spaces, extra characters, accented letters, and values pasted from spreadsheets or email.
  • 3. When moving the pattern into the formula editor, double every backslash and remove the ^ and $ if you prefer. Then run Check Syntax.
  • 4. Optionally, run the pattern in Apex Execute Anonymous with Pattern.matches(), which also uses Java-style syntax and whole-string matching. Treat this as a close approximation, not proof that the formula engine behaves the same way.
  • 5. Activate the rule in a sandbox. Create and edit test records through the user interface and through any import tool or integration that writes to the field in production.
  • 6. Check existing data before activating in production. A validation rule runs whenever a record is saved, so an old non-matching value can block a user who is only editing a different field. Use ISCHANGED() or ISNEW() to limit the rule to new or edited values where that fits your process.
String pattern = '\\d{5}(-\\d{4})?';
for (String v : new List<String>{'12345', '12345-6789', '1234', '12345 '}) {
    System.debug(v + ' => ' + Pattern.matches(pattern, v));
}

The table below shows the expected outcome for the ZIP code rule. These results follow from the pattern's logic. They are not recorded test output.

Input | Pattern matches? | Rule shows error?
12345 | Yes | No
12345-6789 | Yes | No
1234 | No | Yes
12345-678 | No | Yes
ABCDE | No | Yes
12345 followed by a trailing space | No, if the space is stored | Yes, if the space is stored
Blank | Not evaluated (ISBLANK check) | No

Whether leading or trailing spaces are actually stored can depend on how the value is entered, such as through the user interface, an import tool or an API integration. Test each entry path instead of assuming. If whitespace should be ignored, apply TRIM() to the field inside REGEX.

Readability and copy/paste pitfalls

Copying the pattern itself can introduce errors. Text copied from documents, chat tools or web pages may contain curly quotation marks, non-breaking spaces or zero-width characters. Curly quotes usually cause a syntax error, which is at least visible. An invisible character inside the pattern is worse: the pattern then quietly requires a character that users never type. Retype the quotes in the formula editor, and if a rule rejects values it should accept, inspect the pattern with a tool that shows each character's code point.

User input has the same problem. Values pasted from spreadsheets, PDFs or email can contain non-breaking spaces or trailing whitespace that look identical to normal text. The user then gets an error on a value that appears correct. Depending on how strict the field must be, you can wrap the field in TRIM(), widen the pattern to allow harmless variation, or say in the error message that extra spaces are not allowed.

Non-ASCII text needs care. In Java's default mode, \d covers only the digits 0 through 9, and \w covers only unaccented Latin letters, digits and the underscore. Patterns built on \w or on ranges like [A-Za-z] will reject names with accented letters or non-Latin scripts. Java syntax includes Unicode property classes such as \p{L}, which matches any letter (entered as \p{L} in a formula). Confirm in a sandbox that it behaves as expected in your org before relying on it.

Users see the error message, not the pattern. Write the message in plain language, include an example of an accepted value (for example, 12345 or 12345-6789), and do not paste the regex into the message. Display the error at the field rather than at the top of the page, so the message stays next to the input it refers to. This review has no tested evidence on how specific screen readers announce Salesforce validation errors. If accessibility matters for your users, test with the assistive technology they actually use.

Use the validation rule's Description field to explain the pattern in words and list the values you tested. Whoever maintains the rule next can then change it without having to reverse-engineer the expression.

What this review could not verify

No measured test results, version-specific limits or performance data were available for this review. Formula length and compiled-size limits, and the exact set of supported regex constructs, are defined in current Salesforce documentation and may change between releases. Check that documentation before relying on lookarounds, Unicode classes or very long patterns, and confirm behavior in a sandbox in every case.

Bottom line

REGEX in a validation rule is a good choice for checking fixed-format text, as long as you allow for whole-string matching, double backslashes, blank values and pasted input. When a field type or a simple formula function can do the same check, use that instead: it is easier to read, easier to maintain and less likely to reject valid data.