Logic and expressions
Behaviour lives in the logic section as a flat list of rules. Each names the
field it applies to; order does not matter, because evaluation order comes from
what depends on what.
{ "logic": { "rules": [ { "target": "canton", "kind": "visible", "cel": "country == 'CH'" }, { "target": "subtotal", "kind": "computed", "cel": "price * qty" }, { "target": "reason", "kind": "required", "cel": "vip == true" }, { "target": "qty", "kind": "validate", "cel": "qty == null || qty <= 100.0", "code": "tooMany", "message": "We take orders of up to 100 at a time." } ] }}The five kinds
Section titled “The five kinds”| Kind | While the expression is true |
|---|---|
visible |
the field is shown |
disabled |
the field is greyed out but keeps its answer |
required |
the field is required, on top of any fixed required |
computed |
the result is written into the field, and nothing else writes it (below) |
validate |
false means the field carries the error named by code |
A field may carry one rule per kind — two visibility rules would have no defined
winner, and silently picking one is worse than refusing. validate is the
exception: each is an independent check, so a field can have as many as it needs.
What a rule says
Section titled “What a rule says”A validate rule’s code is what the field carries and a submission’s report holds — a word
for machines. What the person reads is the rule’s message: text, or a reference into the
catalogue, said in the form’s language under the field and in the error summary, and for the
same code when the server sends it back. Say what would be accepted, not only that something
is wrong.
A message needs a code, and no other rule on the field may share it. A rule without a message
has its code said as it is written, so give every rule a person can fail one. The builder asks
for it before it adds the rule. Spec version 5
(0198).
Rules inside repeater rows
Section titled “Rules inside repeater rows”Target a row member and the rule runs once per row, with two extra names in
scope: item (the row) and index (its position).
{ "target": "items[].lineTotal", "kind": "computed", "cel": "item.price * item.qty" }{ "target": "items[].qty", "kind": "validate", "cel": "item.qty == null || item.qty > 0.0", "code": "notPositive" }Errors land on the instance that failed — items[1].qty — not on the template.
Target the repeater itself — items, without the brackets — and the rule is about the rows
as a whole. A validate rule reads them as a list, size(items) <= 3, and its error lands on
items; required asks for at least one row; visible and disabled take the rows with the
repeater. The repeater’s own minItems and maxItems are checked the same way, with the
codes a selectboxes reports for the same questions, and a renderer offers no add button
past maxItems and no remove button at minItems
(0184).
Where the add button was, a full repeater says so, No more can be added: 3 at most., in a
status region a screen reader hears as it fills
(0220).
A computed field is read-only
Section titled “A computed field is read-only”Only its rule writes a computed field. A value typed into it, set on it with
setValue or handed in with the form — a resumed draft, a prefill, and on the
server the request body — is not kept, so what is stored is always what the rule
wrote. While the expression cannot be evaluated, because an input it reads is
still empty, the rule writes nothing: the field keeps the value the rule wrote
last, or stays empty.
The field snapshot says so with readOnly, and both renderers draw the text,
paragraph, number, date, time and date-and-time controls with readonly, which
leaves the value in the tab order and announced as read-only. Not disabled:
that would take it out of the tab order and grey out a number somebody is meant
to read.
Every other control is drawn as the field’s answer in words, in one read-only text box labelled by the field. That covers a tick box, a choice, a list, a ranking or a matrix, a rating, a slider, a typeahead or a tag picker, rich text, a file, a signature, and a text box with a scanner. A computed tick box reads Yes or No, a choice its option’s label, and a list the labels joined as the language joins them. Nothing in it can be ticked or chosen, so the screen never shows an answer the form does not hold. A control a host registers for the field’s path still draws it (0216).
A rule may compute a whole repeater, its expression returning the rows. Each field in its rows is
then the rule’s too: drawn read-only, or as its answer in words, with no button to add, remove or
move a row
(0218).
A row whose values are of more than one type needs dyn(), since a map literal is typed by its
values: [{'drug': dyn('A'), 'given': dyn(true)}].
What this does not do:
- A computed field whose options come from a source is said by its stored value, not its label.
- No shipped theme styles a read-only box differently from one that takes
typing. If yours should look like a result rather than a question, style
[readonly].
Why CEL
Section titled “Why CEL”Expressions are Common Expression Language, not a JavaScript subset and not JSONLogic. Four reasons, in order of weight:
- It cannot loop. CEL is non-Turing-complete by construction: no loops, no recursion, no user-defined functions, guaranteed termination. That is a property of the language, not a sandbox somebody has to keep patching.
- It is typed, and checked when you save.
age > "eighteen"is refused at publish time, with a message for the author. - Its syntax tree names exactly what it reads. That is what lets the engine build a dependency graph and detect cycles before anything runs.
- It is readable.
total > 50 && country == 'CH'survives a code review; the JSONLogic equivalent is nested arrays.
What the engine refuses outright
Section titled “What the engine refuses outright”Compilation happens once, when the engine is built — which is also what the server does at publish time. A form is refused if:
- an expression does not parse, or references a field that does not exist;
- it returns the wrong type for its kind (
visiblemust produce a boolean); - it calls something its kind does not allow — the list is below;
- the computed rules form a cycle.
That last one matters most. Because dependencies are known before evaluation, a
form where price computes from qty and qty computes from price is
rejected when it is saved, with the cycle named — rather than hanging in a
browser somewhere.
A dependency is a field, not the group it is in. A computed field reads the
fields its expression names, and so it may read the other fields of its own
group: addr.label computed as "in " + addr.city is accepted. What it may not
read is something that holds it. size(addr) reads the whole group, the field
being computed included, and item the whole row, so a computed field reading
either is refused as a cycle, named by its fields: addr.label -> addr.label. A
read waits for every rule that writes what it reads: a field computed from a
list’s rows runs after the rules that compute them, wherever the list is, and a
rule writing inside a field another rule computes whole runs after that rule.
A row rule reads its own list one way at the top level and another inside a
group. At the top level a row that reads its list whole reads its own row, so
lines[].count computed as double(size(lines)) is refused, while a row
reading another row by position waits for the member it names, so
lines[].count computed as lines[0].qty * 1.0 is accepted. Inside a group a
row rule may read any list inside a group, or any group, whole, and waits for
none of their rows: order.lines[].count computed as double(size(order.lines))
is accepted, and so are the row before, order.lines[index - 1].qty, the last
row, index == size(order.lines) - 1, and another list’s count,
size(order.other) or size(other.lines). Such a rule runs after the rules on
every top-level field, then in the order the document lists the rules, a rule
another of them waits for moved ahead of it, and reads those rows as that order
leaves them: a member another row rule computes is this pass’s value if that
rule comes first and the pass before’s if it comes after, and the rule’s own
member always the pass before’s. So a running total down the rows (below), or a
count of rows whose computed member passes a test, can be a change behind, and
can change if the rules are moved. Every release’s code reads such a rule that
way, and it is kept so that the versions published with one go on opening.
Any other loop is refused, at the top level and inside groups alike: a field
outside the rows computed from them and read back into them, a count computed as
double(size(order.lines)) and read in the rows (read the count in the row
itself instead), a row whose member reads the group in its own row whole, or a
row reading another row’s member, so order.lines[].count computed as
index == 0 ? 1.0 : order.lines[0].count + 1.0 is refused.
Before 2026-11-22 a dependency was the field’s top-level name. That refused a
group’s field reading a sibling and a top-level row reading another by position,
ran a field reading the rows of a list inside a group before those rows were
computed, and accepted those loops: they computed nothing, or values the server’s
replay did not store, or, for a count read back into its rows, the right one. A
version published with one no longer opens;
MIGRATIONS.md
says how to find one.
What an expression may call
Section titled “What an expression may call”Each kind allows a fixed set of functions, and a form calling anything else is refused when the
engine is built, with the set named in the error. Operators are not on it: arithmetic,
comparison, &&, ||, ? :, in and indexing work in every kind.
| For | Functions | Allowed in |
|---|---|---|
| Lists and presence | size has all exists exists_one filter map |
every kind |
| Text | startsWith endsWith contains matches lowerAscii upperAscii trim indexOf lastIndexOf substring split join |
every kind |
| Conversions | bool int double string dyn type timestamp duration |
every kind |
| The parts of a date handed in | getFullYear getMonth getDayOfMonth getDayOfYear getDayOfWeek getDate getHours getMinutes getSeconds getMilliseconds |
every kind |
| Money | dec round divide |
every kind |
| The clock, injected (below) | now today |
every kind |
| Chance, stored with the answer | random |
computed |
random is the one a kind withholds: a visible or required rule that flipped on a coin toss
would make a form behave differently each time it was opened, and unverifiable on the server.
A caller with nothing to capture them in can refuse the clock and chance. A form captures
now, today and random with the submission (below), so replaying it gives
what the person saw. A program that calls @formancy/expressions itself and must give the same
answer for the same values every time, such as a report whose preview has to be the PDF, has
nowhere to keep them. It compiles with reproducible: true, which refuses all three in any kind,
at the call, with the reason in the hint
(0228):
compile('total * dec("1.077")', { kind: 'computed', variables, reproducible: true }) // compilescompile('today()', { kind: 'computed', variables, reproducible: true }) // function_not_allowedIt is an option of the compiler, not something a document can say: a form’s rules are compiled as their kind allows.
A compiled program says what it calls, and where its arithmetic is not exact. Beside
references, the paths it reads, a Program carries calls, each function it calls with the
span of the call, and inexact, each place it computes through a double, named where the double
is outermost, or divides integers, which drops the remainder
(0229).
int(double("4.35") * 100.0) is an int that evaluates to 434; its inexact names
double("4.35") * 100.0. Both are read from the checked expression, so a value the checker types
dyn is named in neither: declare the type of a value that must be exact.
A caller can declare a variable by member, so each member is checked as its own type. A
map makes every member dyn to the checker, so params.copies + "x" passes and
row.amount == dec("1") is refused. Declared by member, row.amount is a decimal, a member the
declaration does not name is refused with the ones it does, and row read whole, in a list, a
map, a branch or as the result, is refused as variable_read_whole, because it would hand its
members on as dyn (0231). When the expression runs, each member is converted as a variable of
its type is, so an int member can arrive as a JSON number and a decimal one as a string:
const variables = { row: { amount: 'decimal', copies: 'int' }, params: { duplex: 'bool' } }compile('row.amount * dec("2")', { kind: 'computed', variables }) // compiles, a decimalcompile('row.amont > dec("0")', { kind: 'computed', variables }) // No such key: amont, hint "row declares amount, copies."compile('[row].size()', { kind: 'computed', variables }) // variable_read_wholeThe engine does not declare a form’s groups or rows this way: their members stay dyn, because
refusing what that lets through would make documents that publish today invalid.
A map an expression writes cannot hold the keys constructor, prototype or __proto__: the
CEL library leaves them out of a literal, as a defence of its own, so {"constructor": item.name}
is {}. A map it reads can — a group or a row with a field keyed constructor is read like any
other (0185).
No function adds up a list
Section titled “No function adds up a list”There is no sum, no fold and no reduce. map and filter make a list, and the only
function that turns one into a number is size(), which counts it. sum(fees.map(f, f.amount))
is refused when the form is built, and so is every other spelling of a total, so a total over a
repeater’s rows cannot be written as one expression. What a form can do instead:
- Ask the question the total was for. “Is any fee over the limit” is
fees.exists(f, has(f.amount) && f.amount != null && f.amount > 500.0), which is what the Angular starter’s expense claim asks for the same reason. - Keep the rows, and add them up where they arrive. The stored submission holds every row, so a webhook’s receiver or a report can total them. The form shows no total then.
- Add the rows up one by one, and cap the repeater at the rows the total names:
{ "key": "fees", "type": "repeater", "maxItems": 3, "fields": [{ "key": "amount", "type": "number" }] }{ "target": "total", "kind": "computed", "cel": "(size(fees) > 0 && 'amount' in fees[0] && fees[0].amount != null ? fees[0].amount : 0.0) + (size(fees) > 1 && 'amount' in fees[1] && fees[1].amount != null ? fees[1].amount : 0.0) + (size(fees) > 2 && 'amount' in fees[2] && fees[2].amount != null ? fees[2].amount : 0.0)" }The last is the one that shows a total, and it costs a cap on the rows. Each row is a term
written out, and under the limit on how large one expression may be, this shape stops at 10 rows.
Every term asks for its row, then for the row’s amount, then whether it is answered, because a
row the add button made has no amount at all until somebody types one: read without the middle
guard, one untouched row stops the whole total, which keeps whatever it said before. Outside a
row rule has() cannot take an indexed row, so the guard is in.
The cap is the repeater’s own maxItems, set to the number of rows the total names. The add
button is not offered past it, and a submission with more rows — a draft, a script, a client
that never drew the button — is refused with maxItems in the browser and on the server, so no
row is ever left out of the total.
Until 2026-10-18 this page put the cap in a validate rule on the total, size(fees) <= 3,
because maxItems capped nothing and a rule aimed at the repeater was never run. Both are
enforced now (0184),
and a form that kept the rule keeps working: it refuses the same fourth row, under the total
rather than on the repeater.
A running total down the rows does not get round it: a row rule that reads fees reads its own
row, and the form is refused as a cycle. Inside a group it is not refused, because a row rule
there may read its own list whole, and it is wrong: the row before is read as the pass before left
it, so a total is a change behind in the browser, and the server’s replay, one pass from the
answers, stores the first row’s and none after it. Every release’s code reads it so, and it is kept
only so that versions published with one go on opening; do not write one. Counting characters — a
string per row as long as its amount, joined, and size() taken — adds up whole numbers no larger
than the longest string literal an expression may hold, and nothing else. It is a trick and not a
total, and nobody reading the rule would see a sum in it.
A function that adds a list up is not in the format, and adding one costs a spec version; the roadmap says what else it takes.
A rule that reads a field you removed
Section titled “A rule that reads a field you removed”The builder keeps these in step: renaming a field, or unwrapping a group, rewrites every rule that names it. A document you write by hand, generate, or have an agent compose has no such help — and a rule reading a path no field provides is the quietest mistake in the format. It compiles, it publishes, it evaluates to nothing, and a conditionally visible field is simply never shown again.
How far the format catches it:
| What the rule reads | At publish |
|---|---|
an unknown top-level field — gone == "8000" |
refused, 422 |
an unknown member of a group — address.nope |
published, with a warning |
an unknown member of a row — item.nope |
published, with a warning |
The first is refused because the engine compiles each rule against the fields that
exist. The other two type-check, because a member of a map is dynamic — and they
are the cases that bite, since inside a group the data path (address.city) and
the field’s own key (city) are different things.
The warning comes back on the publish’s 201. It is a warning rather than a
refusal because published spec versions are frozen, and a reader that started
rejecting documents it used to accept would break that contract. If you want it to
be a gate, Self-hosting shows the one-line check.
What it tolerates at runtime
Section titled “What it tolerates at runtime”A half-filled form produces evaluation failures constantly; those are normal control flow, and the direction of failure is chosen per kind:
- Metadata fails open. A
visiblerule that cannot evaluate shows the field. Hiding on error would silently swallow whatever the person had typed. - Validation fails closed. A
validaterule that cannot evaluate cannot vouch for the value, so the field is marked invalid. The author sees their broken rule instead of bad data getting through.
Which means an unanswered field needs guarding, and != null is not the guard
Section titled “Which means an unanswered field needs guarding, and != null is not the guard”Fails-open is the right default and it has a consequence worth knowing before you write your first rule: a condition that errors on an empty form shows the field it was meant to hide, from the start, with nothing to say so.
Several shapes error, and the worst of them look defensive:
| Condition | On an untouched form |
|---|---|
!needsVisa |
errors — CEL has no ! for null |
address.country == "CH" |
errors — the group is null, so reading a member of it fails |
address.country != null && address.country == "CH" |
errors — it still has to read the path to compare it |
age > 18.0 |
errors — CEL has no > between null and a number |
"gift" in item.tags |
errors — in a repeater row an untouched list is null, not [] |
has(item.tags) && "gift" in item.tags |
errors — a row has every key, so has() is true and the value is still null |
needsVisa != true |
true |
has(address.country) && address.country == "CH" |
false |
age != null && age > 18.0 |
false |
item.tags != null && "gift" in item.tags |
false |
The pattern: comparing against null cannot rescue a read that fails, because
the read happens first. For a top-level field, compare against the value you
mean — needsVisa != true rather than !needsVisa. For a path inside a group,
test presence with has(...), which is the only one of these that answers
rather than failing.
A repeater row is the other way round. The engine presents a row with every key
there and null until answered, so has() is always true in a row and answers
nothing; there, != null is the guard — item.tags != null before in or
size(), item.qty != null before >. A list is the case to watch: at the top
level an untouched list is [], and so is a repeater handed null, and "gift" in extras is simply false, while the same condition in a row errors. The builder’s condition editor writes these guards
itself.
Both of these shipped in this project’s own demo and were found by running it
against an engine rather than by reading it. A visible rule that is wrong this
way is invisible precisely because it fails open: the field is simply always
there.
The builder’s condition editor wrote two of these shapes itself — a comparison
on a field inside a group, and a bound on a number — until 2026-10-09. It now asks
first: has(...) before reading into a group, != null before ordering or
searching a value, and a length for a list of ticks, which an empty list does not
have. A rule written by an earlier builder keeps the expression it was written with,
because the expression is what is stored; this table is how to recognise one
(0127).
It also wrote a date and time as the author’s own wall clock, in every release
through 0.13.0: departs > "2026-10-08T10:30", which is what its local date-and-time
box holds, compared as text with answers stored in UTC with seconds. Such a rule is
off by the author’s offset from UTC, and one using is never holds. The editor now
writes the instant the author chose, read in their own zone and written as every
answer is: departs > "2026-10-08T08:30:00Z", from Zurich in October. A comparison
with a date and time you write yourself has the same rule to follow: write the instant
in UTC, with seconds and Z. An older rule whose literal has neither is one to remove
and add again
(0235).
A publish names each such rule in a warning, and any rule comparing a date or a time
with text in another shape
(0236).
A time or an instant with a precision
Section titled “A time or an instant with a precision”A field with a precision (Schema)
has answers of one width, "09:30:00.000" at precision 3, and text of two widths does not order as
time does: "2026-10-08T10:34:56.000Z" < "2026-10-08T10:34:56Z" is true for the same instant.
So for such a field a publish refuses a rule comparing it with a literal not at its width, or
with a temporal field of another shape, and says what to write instead, which depends on what is
compared:
- A literal: write it at the field’s width,
"09:30:00.000". On a date and time whose literal is an instant, comparing both sides throughtimestamp()works too. - Two fields of one type: give both one precision. For a date and time, comparing
timestamp(startedAt) < timestamp(endedAt)works too. - A date and a date and time: different kinds of answer, which compare as text only within one kind. Which day an instant falls on depends on a time zone, so there is no expression to copy that means “the same day” without choosing one, and the sentence offers none. The instant’s first ten characters are its day in UTC: an instant late at night in New York is the next day there.
- A time and either: different kinds too, and there is nothing to write that compares them; compare each with a value of its own kind.
timestamp() takes a date and time only. On a time or a date it is an error, and a visible rule
that errors shows its field, so the sentence offers it nowhere else. It compares to the millisecond
and no finer: it keeps three digits after the seconds and cuts the rest, so two answers a
microsecond apart compare equal. Where the digits matter, give the fields one precision and compare
them as they are. A field without a precision is warned about instead, as above.
opens != "" on such a field is refused too, because an unanswered field holds null, never "":
ask opens != null, or item.at != null in a row, or has(stay.at) inside a group. opens == ""
is told the opposite, opens == null or !has(stay.at), since the answered test copied into it
would turn the rule round.
One comparison is not seen: through a list rule’s own variable. In
steps.all(s, s.at >= startedAt), s.at is not a field to the check, so the rule publishes
whatever the precisions of steps[].at and startedAt are, and if they differ it compares wrongly.
Give the fields a list rule compares one precision, or, for two dates and times, compare them
with timestamp(). The condition editor writes no list rule, so only one written by hand meets
this (0238).
Nothing ambient
Section titled “Nothing ambient”now(), today() and random() do not read a clock — they read values the
caller injected, frozen for the whole evaluation pass:
createFormEngine({ schema, capabilities: { now: () => Date.now(), today: () => new Date().toISOString().slice(0, 10), random: () => Math.random(), },})This is why the server can replay a submission months later and get
byte-identical computed values, and why a schema with logic rules refuses to
build without capabilities rather than quietly reaching for Date.now.
Money is not a double
Section titled “Money is not a double”A decimal type backed by scaled integers exists precisely because 0.1 + 0.2
is the wrong answer to give someone about their invoice. Mixing decimals with
plain numbers is a check-time error, with a hint naming the fix:
price * 0.19 // rejected: Write dec("0.19") instead of 0.19price * dec("0.19") // exactdivide(total, dec("3"), 2) // division needs explicit places — it cannot stay exactCost is bounded, deterministically
Section titled “Cost is bounded, deterministically”Evaluation is metered by counting steps, never by a wall clock — a submission that passed in the browser must not fail its replay on a slower server. Values entering an expression are bounded too (string length, list and map size, nesting depth), so a large payload is refused at the boundary instead of being discovered to be expensive halfway through.
No expression ever reaches eval or new Function. formancy runs under a
strict script-src 'self' policy with no unsafe-eval and no configuration.