Rego is the declarative policy language used by Open Policy Agent (OPA) for writing and enforcing policies across cloud-native stacks, featuring data-driven rules, comprehensions, and 200+ built-in functions for infrastructure, security, and compliance automation.
Overall
score
97%
Create a data validation policy in Rego that validates a user registration payload and collects all constraint violations.
Create validation.rego with package data.validation and import rego.v1.
The policy evaluates the following input structure:
{
"name": "Alice Smith",
"email": "alice@example.com",
"age": 30,
"role": "user"
}Define a multi-value violations rule (a set of strings) — do not use a boolean pattern. Each broken constraint should add a distinct error message to the set. A valid payload must produce an empty set.
Implement the following checks:
1. Required name
input.name must be present and must be a non-empty string. Violation message:
name is required and must be a non-empty string2. Valid email
input.email must be present and must match the regular expression ^[^@]+@[^@]+\.[^@]+$. Violation message:
email is required and must be a valid email address3. Age range
input.age must be a number greater than or equal to 18 and less than or equal to 120. Produce separate messages for each case:
age must be at least 18
age must be no greater than 1204. Valid role
input.role must be one of: "admin", "user", "readonly". Violation message:
role must be one of: admin, user, readonlyCreate validation_test.rego with package data.validation_test and import rego.v1.
Use the with input as { ... } keyword in every test. Include tests for:
violations must be an empty setname — violations must contain the name messageemail (e.g. "not-an-email") — violations must contain the email messageage below 18 — violations must contain the under-age messageage above 120 — violations must contain the over-age messagerole — violations must contain the role messageRun opa test . -v and confirm all tests pass.