Rules
Rules are declarative contracts that validate inputs, outputs, and state transitions. They enforce constraints at runtime and produce clear error messages when violated.
Built-in Rules
R-Think includes a set of built-in rules covering common validation patterns.
- required - Ensures a field is present.
- type - Validates the JavaScript type of a field.
- bounded - Validates numeric ranges.
- matches - Validates against a regular expression.
- enum - Validates against a set of allowed values.
- minLength / maxLength - Validates string or array length.
- custom - Defines validation logic with a function.
Defining Rules
Rules are defined as an array and attached to a runtime or protocol. They are evaluated automatically before each step executes.
rules.ts typescript
import { Rule } from '@r-think/core';
const rules = [
Rule.required('applicationId'),
Rule.type('applicationId', 'string'),
Rule.matches('email', /^[^\s@]+@[^\s@]+\.[^\s@]+$/),
Rule.bounded('score', 0, 100),
Rule.enum('status', ['pending', 'approved', 'rejected']),
Rule.custom('riskLevel', (value) => {
return value >= 0 && value <= 10;
}, 'Risk level must be between 0 and 10')
]; Custom Rules
When built-in rules are insufficient, define custom rules using the Rule.custom factory. The validator function receives the value and context, returning true for pass or a string error message for fail.
custom-rule.ts typescript
Rule.custom('portfolio', (value, ctx) => {
if (!Array.isArray(value)) return 'Portfolio must be an array';
if (value.length === 0) return 'Portfolio cannot be empty';
const hasValidAssets = value.every(asset => asset.value > 0);
if (!hasValidAssets) return 'All assets must have positive value';
return true;
}, 'Portfolio validation failed'); Rule Groups
Rules can be grouped and applied conditionally. Use RuleGroup to organize rules by concern: input validation, output validation, and transition validation.
Rule Evaluation Order
Rules are evaluated in the order they are defined. If a required rule fails, subsequent rules for the same field are not evaluated.