ObjectStackObjectStack

Validation metadata — declare the checks

Define data integrity rules — formula conditions, format, cross-field checks, state machine transitions, and more

Validation rules enforce data integrity at the platform level. They run automatically on the write path (insert/update), preventing invalid data from being saved. A validation rule is a deterministic, synchronous, side-effect-free predicate over a single record — it must be decidable from the incoming write (and, on update, the prior record) with no I/O. ObjectStack supports 6 validation types: script, state_machine, format, cross_field, json_schema, and conditional.

Three patterns that look like validation rules are deliberately not rule types, because each needs I/O or is a client-side concern. Use the layer that already does each one correctly:

  • Uniqueness → a unique index (ObjectSchema.indexes, { fields, unique: 'organization' | 'global' } — state the scope, ADR-0120) or field-level unique. A SELECT-then-INSERT rule is inherently racy (TOCTOU); a DB unique constraint is not.
  • Async / remote validation → a client-form concern, and an SSRF/latency hazard on the server write path. Keep it in the form layer, or enforce the invariant with a unique index / lifecycle hook.
  • Custom handler → a beforeInsert / beforeUpdate lifecycle hook, the supported extension point for arbitrary validation code.
  • Delete-time guards → a beforeDelete lifecycle hook. Validation rules run only on insert/update (a delete carries no record payload to validate), so there is no 'delete' validation event — block or gate deletions from a beforeDelete hook.

Basic Structure

Validations are defined on an Object's validations array:

import { ObjectSchema, Field } from '@objectstack/spec/data';

export const Order = ObjectSchema.create({
  name: 'order',
  sharingModel: 'private',
  label: 'Order',
  fields: {
    amount: Field.currency({ label: 'Amount', required: true }),
    status: Field.select({
      label: 'Status',
      options: [
        { label: 'Draft', value: 'draft', default: true },
        { label: 'Submitted', value: 'submitted' },
        { label: 'Approved', value: 'approved' },
        { label: 'Cancelled', value: 'cancelled' },
      ],
    }),
    email: Field.email({ label: 'Contact Email' }),
  },

  validations: [
    {
      name: 'amount_positive',
      type: 'script',
      severity: 'error',
      message: 'Amount must be greater than zero',
      // CEL predicate — TRUE means the record is invalid.
      condition: 'record.amount <= 0',
      events: ['insert', 'update'],
    },
  ],
});

Condition expressions are CEL (evaluated by @objectstack/formula), not Salesforce-style formulas. Reference the incoming record via record.<field>, use ==/!=, &&/||, and helpers like isBlank(x) and has(record.field). A string condition is accepted as authoring shorthand and normalized to { dialect: 'cel', source } at build time.

has(x) is not a null guard. Predicates see a record that is total over the object's declared fields, so has(record.end_date) is true even when the value is NULL — has(a) && has(b) && a < b then reaches null < null, CEL has no overload, and the whole rule aborts (the write is rejected fail-closed). Write record.start_date != null && record.end_date != null && record.end_date < record.start_date instead. Since #4763 the has() form is rejected at build/publish: an ordering or arithmetic operator over a declared nullable field needs a real != null guard. has() over an undeclared key — "was this in the PATCH at all?" — is untouched.

Common Properties

All validation types share these base properties:

PropertyTypeRequiredDescription
namestring✅Unique rule name (snake_case)
labelstringoptionalDisplay label
descriptionstringoptionalDeveloper documentation
activebooleanoptionalIs the rule active (default: true)
severityenumoptional'error' (blocks save), 'warning', 'info' (default: 'error')
messagestring✅User-facing error message
eventsenum[]optionalWhen to run: 'insert', 'update' (default: ['insert', 'update']). No 'delete' — guard deletions with a beforeDelete lifecycle hook
prioritynumberoptionalExecution order (0-9999, lower runs first, default: 100)
tagsstring[]optionalCategorization tags

Severity Levels

SeverityBehavior
errorPrevents the record from being saved
warningAllows the save; advisory only — returned to the caller in the write answer's warnings, and logged server-side
infoInformational message, no blocking; returned and logged the same way as warning

Advisory rules (warning / info) are reported, never enforced: on an ordinary write each hit is logged as it happens; on a seed/boot load a run's hits are folded into one summary line per rule; and an update touching only platform-injected system columns does not re-evaluate them at all, so a row is reported once rather than once per write (#13889).

The write's caller sees them too. A create, an update or a clone whose record trips an advisory rule still succeeds, and its answer carries warnings, one entry per rule hit: the rule's name as rule, its severity, the field it is about (_record for an object-level rule), the finding code and your message. A client shows that message to the person who saved. A write with no hit has no warnings key at all.

{
  "object": "task",
  "id": "tsk_001",
  "record": { "id": "tsk_001", "name": "Internal chore", "related_to": null },
  "warnings": [
    {
      "rule": "related_to_required",
      "severity": "warning",
      "field": "_record",
      "code": "rule_violation",
      "message": "At least one related record should be selected."
    }
  ]
}

Only the hits of that one write are listed: a record a hook or a flow writes while handling it reports its own hits to its own caller, not into this answer. The validate-only preview (validateData, and an import's dry run) appends the same entries to each accepted row's warnings, after any value-shape findings the deployment admits. A rule whose condition could not be evaluated is not a hit: it is reported in the server log only.

Validation Types

Script Validation

Formula-based validation using expressions:

{
  name: 'close_date_required',
  type: 'script',
  severity: 'error',
  message: 'Close date is required for closed deals',
  condition: "record.status == 'closed_won' && isBlank(record.close_date)",
  events: ['insert', 'update'],
}

The condition is a CEL predicate and should evaluate to true when the data is invalid.

A predicate that cannot be evaluated (parse error, unbound variable, a comparison CEL has no overload for) rejects the write with VALIDATION_FAILED, naming the rule and — when the fault is a missing key — the key the predicate read and how to fix it. Until protocol 17 such a rule was logged at WARN and skipped, so the write went through while the rule stayed declared and enforced nothing; a validation exists to reject a write, and "the rule could not be checked" must never resolve to "allowed" (#4649). severity still governs blocking — an unevaluable warning / info rule is logged and does not throw, on the writes where advisory rules are evaluated at all (see above).

The record a predicate reads is the stored row overlaid with this write's payload, total over the object's declared fields (null for a declared field present in neither), on update as well as insert — so a driver that stores only the columns it wrote no longer decides whether an expression is evaluable. That totality is also why has() is not a null guard: see the callout above.

Uniqueness (use an index, not a validation rule)

There is no uniqueness validation type. A SELECT-then-INSERT rule is inherently racy (TOCTOU), so uniqueness is enforced at the data layer instead:

// Field-level uniqueness
email: Field.email({ label: 'Contact Email', unique: 'organization' }),

// Composite / scoped uniqueness via ObjectSchema.indexes
indexes: [
  { fields: ['code'], unique: 'organization' },
]

type and partial were retired at protocol 17 (#5248, #4943) — IndexSchema is a strict object declaring exactly name / fields / unique, so authoring either is now a rejection with guidance, not a silent strip. A partial index is built at the database layer (a runtime migration issuing CREATE UNIQUE INDEX … WHERE), not on the declaration surface; see Objects.

Format Validation

Validate against a regex pattern or standard format:

// Regex pattern
{
  name: 'phone_format',
  type: 'format',
  severity: 'error',
  message: 'Phone must match format: +1-XXX-XXX-XXXX',
  field: 'phone',
  regex: '^\\+1-\\d{3}-\\d{3}-\\d{4}$',
  events: ['insert', 'update'],
}

// Built-in format
{
  name: 'website_format',
  type: 'format',
  severity: 'error',
  message: 'Website must be a valid URL',
  field: 'website',
  format: 'url',
  events: ['insert', 'update'],
}
PropertyTypeDescription
fieldstringTarget field
regexstringCustom regex pattern
formatenumBuilt-in format: 'email', 'url', 'phone', 'json'

State Machine Validation

Enforce allowed state transitions:

{
  name: 'order_status_transitions',
  type: 'state_machine',
  severity: 'error',
  message: 'Invalid status transition',
  field: 'status',
  // Which states a record may be CREATED in (the FSM entry point).
  initialStates: ['draft'],
  transitions: {
    draft: ['submitted', 'cancelled'],
    submitted: ['approved', 'rejected', 'cancelled'],
    approved: ['completed'],
    rejected: ['draft'],
    cancelled: [],
    completed: [],
  },
}
PropertyTypeDescription
fieldstringState field name
transitionsRecord<string, string[]>Map of current state → allowed next states (enforced on update)
initialStatesstring[] (optional)States a record may be created in. Server-rejects an insert whose state field is outside this list — without it a select field permits any declared option as the initial value (a record could be born already approved). An active machine that runs on insert (its events include insert, the default) with no initialStates, or an empty list, is refused at publish and by os validate (state-machine-no-initial-states): "without initialStates a record can be created already approved or done and skip the whole process." Only a machine whose events leave out insert (e.g. events: ['update']) may omit it, "because the engine never runs it on create and would never read its initialStates."

transitions governs updates; initialStates governs the create. A rule may declare either or both.

Seed data is exempt from the state machine (#3433). Curated fixtures loaded by SeedLoaderService may be born in any declared state — a project seeded completed, an opportunity closed_won — without initialStates or transitions being enforced. Seeds are established facts, not lifecycle events. Every other validation still applies, and os lint warns if a seeded value is not a state the machine declares, so typos surface before boot.

Cross-Field Validation

Validate relationships between multiple fields:

{
  name: 'date_range_valid',
  type: 'cross_field',
  severity: 'error',
  message: 'End date must be after start date',
  fields: ['start_date', 'end_date'],
  condition: 'record.end_date <= record.start_date',
  events: ['insert', 'update'],
}

cross_field evaluates identically to script — both run the same CEL predicate. The only difference is fields[0], which labels the field the error attaches to (a plain script error attaches to the record). The remaining fields are advisory/documentation. Reach for cross_field when you want the error targeted at a specific field; otherwise script is equivalent.

JSON Schema Validation

Validate JSON data against a JSON Schema:

{
  name: 'config_schema',
  type: 'json_schema',
  severity: 'error',
  message: 'Configuration JSON is invalid',
  field: 'config',
  schema: {
    type: 'object',
    required: ['host', 'port'],
    properties: {
      host: { type: 'string' },
      port: { type: 'number', minimum: 1, maximum: 65535 },
    },
  },
  events: ['insert', 'update'],
}

Conditional Validation

Apply validation only when a condition is met:

{
  name: 'billing_required_for_paid',
  type: 'conditional',
  message: 'Billing validation',
  when: "record.plan_type == 'paid'",
  then: {
    name: 'billing_address_check',
    type: 'script',
    severity: 'error',
    message: 'Billing address is required for paid plans',
    condition: 'isBlank(record.billing_address)',
  },
  // Optional: a rule to apply when `when` is false
  // otherwise: { ... }
}

The outer conditional evaluates the when CEL predicate, then recurses into then (when true) or otherwise (when false). The nested rule supplies the violation message; the conditional itself carries the required base message.

Priority

When multiple validations exist, priority controls execution order:

// Runs first (lower number = higher priority)
{ name: 'format_check', priority: 10, ... }

// Runs second
{ name: 'uniqueness_check', priority: 50, ... }

// Runs last (default priority)
{ name: 'business_rule', priority: 100, ... }

Complete Example

validations: [
  // Formula validation
  {
    name: 'amount_positive',
    type: 'script',
    severity: 'error',
    message: 'Order amount must be positive',
    condition: 'record.amount != null && record.amount <= 0',
    events: ['insert', 'update'],
    priority: 10,
  },
  // State transition
  {
    name: 'status_flow',
    type: 'state_machine',
    severity: 'error',
    message: 'Invalid status transition',
    field: 'status',
    transitions: {
      draft: ['submitted'],
      submitted: ['approved', 'rejected'],
      approved: ['shipped'],
      rejected: ['draft'],
      shipped: ['delivered'],
    },
    events: ['update'],
    priority: 20,
  },
  // Cross-field
  {
    name: 'shipping_date_after_order',
    type: 'cross_field',
    severity: 'error',
    message: 'Ship date must be after order date',
    fields: ['order_date', 'ship_date'],
    condition: 'record.ship_date < record.order_date',
    events: ['insert', 'update'],
    priority: 40,
  },
]

// Order-number uniqueness is enforced with an index, not a validation rule:
// indexes: [{ fields: ['order_number'], unique: 'global' }]

CEL Functions and Operators

Conditions and formulas use CEL. Logic is expressed with operators (&&, ||, !, ==, !=, ternary cond ? a : b) rather than function calls. The current record is record; the pre-change snapshot is previous. The CEL stdlib functions available include:

FunctionDescriptionExample
isBlank(x)True if null/empty/whitespaceisBlank(record.phone)
isEmpty(x)True if empty collection/stringisEmpty(record.tags)
coalesce(a, b)a if non-null, else bcoalesce(record.nickname, record.name)
today()Current daterecord.close_date <= today()
now()Current datetimerecord.due_at < now()
daysBetween(a, b)Whole days between two datesdaysBetween(record.end_date, today())
upper(s) / lower(s)Case conversionupper(record.sku)
trim(s)Strip whitespacetrim(record.name)
contains(s, sub) / startsWith / endsWithSubstring checkscontains(record.email, "@")
matches(s, regex)Regex testmatches(record.email, "^[^@]+@[^@]+$")
len(x) / size(x)Length / sizelen(record.code) == 6
min(a, b) / max(a, b) / abs(x) / round(x)Numericsmax(record.amount, 0)

To compare against a field's previous value, reference previous.<field> (e.g. record.stage != previous.stage).

Qualify your references. A validation predicate binds only the record namespace, so a bare status == "won" is an unknown variable and the rule cannot be evaluated: an error rule then refuses every write it judges, and a warning / info rule is skipped with a log line and never applied — write record.status == "won". objectstack build flags bare references, unknown fields, and text/boolean fields misused in arithmetic — see Build-time validation.

Best Practices

✅ DO:

  • Validate at the lowest level possible (field > validation rule > trigger)
  • Provide clear, actionable error messages
  • Use appropriate severity levels
  • Test with real-world data

❌ DON'T:

  • Duplicate validations
  • Create overly complex conditions
  • Block legitimate edge cases
  • Use triggers for simple validations

On this page