Contains() Method in Salesforce Apex with Real-Time Examples
The contains() method in Salesforce Apex is a versatile, case-sensitive function used to check if a substring exists within a string or if a value exists in collections like lists or sets. This article explains practical uses such as validating email domains, checking whitespace in account names, routing cases based on keywords, controlling access based on user profiles, and enforcing validation rules through triggers. It offers real-world examples and code snippets demonstrating how contains() simplifies common business logic. Salesforce developers can apply these patterns to make their Apex code more efficient and maintainable.
- Use contains() to check substrings within strings for validation and routing logic.
- Leverage contains() with lists or sets to verify allowed users or profiles.
- Remember contains() is case-sensitive; convert to lowercase if needed.
- Apply contains() in triggers to enforce business validation rules and block invalid records.
- Use containsWhitespace() to detect spaces or whitespace in string fields.
When you start writing Apex code, one thing you quickly realize is that most of your logic depends on checking values. You need to check: Does this field contain a specific word? Does this list already contain this value? Is this user allowed? Is this industry valid? Is this email a duplicate? And in all these situations, one small but powerful method helps you: the contains() method. In this article, we will learn about how to use the contains() method in Salesforce Apex , and along with this, I will explain: Why do we use contains() in Apex Where exactly is it used in real Salesforce projects How it behaves with String, List, and Set Real trigger example What is contains() Method in Salesforce Apex? The contains() method checks whether a value exists within another value.