Rego Built-in Function: contains
contains is a commonly used Rego built-in function that checks if a string contains a substring. The function returns true if the string contains the substring and false otherwise.
Some examples of policy use cases where contains might be used include:
- Simple validation, such as checking if an email contains a
@symbol. - Checking if user input contains restricted words or phrases for content moderation.
If you're looking to check a string that's expected to be at the start or end of a value, you might be better served by one of the following functions:
- Starts With: Checks if a string starts with a specified prefix.
- Any Prefix Match: Checks if a string starts with any of the specified prefixes.
- Ends With: Checks if a string ends with a specified suffix.
- Any Suffix Match: Checks if a string ends with any of the specified suffixes.
These are safer and potentially faster too.
contains only operates on strings, if you're looking to check for the presence of a value in a list you cannot use this function.
If you're looking for the Rego keyword contains for building multi-value rules, you can read
about it in the keywords section.
Examples
Simple email validation
In the example that follows, contains is used to test if
the @ symbol is contained in the supplied email address. This can
be useful as a first check on raw user data.
{}
{
"email": "hello at example.com"
}
package play
import rego.v1
example1 if contains("alice@example.com", "@")
example2 if contains("bob[at]example.com", "@")
example3 if contains(input.email, "@")
| Rule | Output Value | Notes |
|---|---|---|
| example1 | true | |
| example2 | undefined | |
| example3 | Depends on user input |
Keyword checking for content moderation
The contains function is also useful for checking user
text for keywords, certain keywords might not be allowed.
In this example, reasons will be a list of the banned words
found in the input.message.
package play
import rego.v1
banned_words := {"hate", "kill"}
reasons contains word if {
some word in banned_words
contains(input.message, word)
}
{
"message": "i hate apples"
}
{}
| Rule | Output Value |
|---|---|
| reasons | ["hate"] |