Loading

How to Use the Salesforce CONTAINS Function in Formulas and Validation Rules

Дата публикации: May 13, 2026
Описание

The Salesforce CONTAINS function compares two text strings and returns TRUE if the first string contains the second string. It is commonly used in validation rules, workflow rules, and formula fields to check whether a specific word, character, or sequence of characters appears within a text field value.
For reference documentation, see CONTAINS and  Formula Operators and Functions by Context.

Решение

CONTAINS Usage

The CONTAINS function is used for two main purposes:

  1. Search for a specific word or phrase in a text field.
  2. Check if an unknown string or character matches a defined set of allowed strings or characters.

Example 1: Search for a Specific Word in a Text Field

The following formula checks whether the Comments field contains the word "BadWord". The CONTAINS function returns TRUE if "BadWord" appears anywhere in the Comments__c field value, regardless of position.
Formula: CONTAINS(Comments__c, "BadWord")
This returns TRUE if "BadWord" is found anywhere in Comments__c.
Use case: This formula can be used in a validation rule to prevent records from being saved if the Comments field contains prohibited language.

Example 2: Check If a Text Field Contains Only Numeric Characters (Substring Match)

The following formula checks whether the value of TextField__c is a substring of the string "0123456789". This effectively checks if the field value contains only digits from 0–9.
Formula: CONTAINS("0123456789", TextField__c)
This returns TRUE for TextField__c values such as 1, 2, 9, 01, 789, or any other substring of "0123456789".
Important note: This approach matches substrings, not exact characters. For example, it would return TRUE for "01" or "789" because both are substrings of "0123456789".

Example 3: Check Only the First Character of a Field

To check only whether the first character of a field is a digit (0–9), use the LEFT function to limit the comparison to a single character.
Formula: CONTAINS("0123456789", LEFT(TextField__c, 1))
This returns TRUE only if the first character of TextField__c is a digit between 0 and 9.
Important note: When using CONTAINS to compare a string against a defined set, the length of the elements in the set should match the length of the string being compared. An equivalent CASE statement is longer but more reliable.

CONTAINS and Blank Values

The CONTAINS function treats a BLANK (empty) value as TRUE. If you need to exclude blank values from matching, combine CONTAINS with NOT(ISBLANK()). Example: AND(NOT(ISBLANK(Comments__c)), CONTAINS(Comments__c, "BadWord"))
Note: Using NOT directly on CONTAINS does not handle BLANK values — always use NOT(ISBLANK()) separately.

Дополнительные ресурсы

Examples of Advanced Formula Fields


Номер статьи базы знаний

000385300

 
Загрузка
Salesforce Help | Article