ExpressionsMIT
The sandboxed expression language behind conditions, calculations and validation rules, with every operator and function, and the APIs to use it outside forms.
Conditions, calculated values and validation rules are written in a small expression language. It reads like a spreadsheet formula, refers to answers by name in braces, and is evaluated by Birch UI's own parser: never with eval or new Function, so schemas from a database or an end-user editor cannot run code.
{age} >= 18 and {country} = 'GB'
{claimType} in ['motor', 'home'] or {estimatedLoss} > 5000
{firstName} + ' ' + {lastName}
sum({lineItems.amount}) * (1 + {vatRate} / 100)
dateDiff({collectOn}, {returnBy}, 'days') <= 14Where expressions are used#
| Property | Expects | If the expression fails |
|---|---|---|
visibleIf on fields, panels, pages and choices |
true or false | The element stays visible. |
enableIf |
true or false | The element stays enabled. |
requiredIf |
true or false | The field is not required. |
expression on a computed field |
any value | The field is empty. |
expression in an expression validator |
true when valid | The value is accepted. |
Failures are reported through the formError event, and the form keeps working with the safe default in the table.
{fieldName} placeholders, without operators, also work inside markdown content and a repeating section's templateTitle, where they insert the current answer.
Values#
| Syntax | Meaning |
|---|---|
{employmentType} |
The answer to the field named employmentType. Unanswered fields are empty. |
{address.city} |
A property of an object answer. |
{previousJobs[0].employer} |
An entry of a repeating section by index, starting at 0. |
{lineItems.amount} |
A projection: the amount of every entry of lineItems, as a list. Use it with sum(), count() and similar functions. |
'text' or "text" |
A string. Escape quotes with a backslash; \n and \t are a line break and a tab. |
42, 3.5 |
A number. |
true, false |
Booleans. |
null |
No value. undefined means the same. |
['motor', 'home'] |
A list. |
Names of fields must be in braces. A bare word such as age is a syntax error, with a message suggesting {age}.
Inside a repeating section, {panel.x} is a field of the current entry, {panelIndex} its number starting at 1, {parentPanel.x} a field of the enclosing entry in nested sections, and sibling names such as {amount} resolve to the current entry.
Operators#
From lowest to highest precedence:
| Operators | Meaning |
|---|---|
or, || |
Either side is true. |
and, && |
Both sides are true. |
not, ! |
Negation. |
= or ==, != or <> |
Equality. Compares loosely: '5' = 5 and 'true' = true are true. |
<, <=, >, >= |
Comparison of numbers, numeric strings and other strings. ISO dates compare correctly as strings. |
contains, notcontains, not contains |
A list contains a value (or every value of another list), a string contains a substring, or an object has a non-empty property. |
in, not in |
A value is in a list, or a substring of a string. With a list on the left, true if any item matches. |
empty, notempty |
Postfix: {middleName} empty, {photos} notempty. |
+, - |
Addition and subtraction. + joins strings when either side is a string, and concatenates two lists. |
*, /, % |
Multiplication, division and remainder. |
-x, +x |
Unary minus and plus. |
^, ** |
Power, right-associative. |
Parentheses group as usual. Keywords are case-insensitive, so AND and and are the same.
How values behave#
- Empty values are
null, missing answers, empty strings and empty lists. Two empty values are equal; an empty value is not equal to anything else, and comparisons with an empty value are false. - Truthiness:
false, empty values,0and the string'false'are false; everything else is true. - Arithmetic treats empty values as 0. Dividing by zero, or a result that is not a finite number, gives
nullrather thanInfinity.
{discountCode} empty or {discountCode} in ['WINTER26', 'LOYAL10']
{symptoms} contains 'fever'
not ({hasDriverLicence} = true)
round({distanceKm} * 0.45, 2)Functions#
Function names are case-insensitive: dateDiff and datediff are the same function.
Dates#
Dates are ISO strings such as '2026-11-14' or '2026-11-14T09:30', interpreted in the user's local time zone.
| Function | Returns |
|---|---|
today(offsetDays?) |
Today as 'YYYY-MM-DD', optionally shifted: today(-30) is 30 days ago. |
now() |
The current local date and time as 'YYYY-MM-DDTHH:MM'. |
age(date) |
Full years since date. |
dateDiff(from, to, unit?) |
The difference in 'days' (default, calendar days), 'months', 'years', 'hours' or 'minutes'. Months and years count whole units. |
addDays(date, n) |
date plus n days, as 'YYYY-MM-DD'. |
year(date), month(date), day(date) |
Parts of a date. Months are 1 to 12. |
Numbers and lists#
| Function | Returns |
|---|---|
sum(...values) |
The sum of all numbers, flattening lists. Empty and non-numeric values are skipped. |
count(...values) |
The number of non-empty values, flattening lists. |
avg, min, max |
Average, minimum and maximum of the numbers, or null if there are none. |
round(x, digits?) |
x rounded to digits decimal places (0 to 10, default 0). |
floor(x), ceil(x), abs(x) |
Rounding down, rounding up and absolute value. |
number(x) |
x as a number, or null. |
length(x) |
The length of a string or list, or the number of keys of an object. |
Text and logic#
| Function | Returns |
|---|---|
lower(x), upper(x), trim(x) |
Case conversion and whitespace trimming. |
concat(...values) |
All values joined as text. Lists are joined with , . |
string(x) |
x as text. |
contains(haystack, needle) |
Same as the contains operator. |
isEmpty(x), notEmpty(x) |
Same as the empty and notempty operators. |
equals(a, b) |
Same as =. |
iif(condition, whenTrue, whenFalse) |
whenTrue if condition is true, otherwise whenFalse. |
coalesce(...values) |
The first non-empty value. |
iif({employmentType} = 'contractor', {dayRate} * 220, {annualSalary})
coalesce({preferredName}, {firstName})
count({dependants}) > 0
upper(trim({postcode}))Custom functions#
Register your own functions with the functions option. They receive the evaluated arguments and should be fast, pure and synchronous.
const holidays = new Set(['2026-12-25', '2026-12-28', '2027-01-01']);
createForm(container, {
schema: equipmentCheckout,
functions: {
businessDaysBetween: (from, to) => {
const start = new Date(`${String(from)}T00:00:00Z`);
const end = new Date(`${String(to)}T00:00:00Z`);
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return null;
let days = 0;
for (const day = new Date(start); day < end; day.setUTCDate(day.getUTCDate() + 1)) {
const weekday = day.getUTCDay();
if (weekday !== 0 && weekday !== 6 && !holidays.has(day.toISOString().slice(0, 10))) days++;
}
return days;
},
},
});businessDaysBetween({collectOn}, {returnBy}) <= 10Custom names are matched without regard to case. A custom function with the same name as a built-in one takes precedence. If a function throws, the error is reported through formError and the call returns null. An unknown function is also reported and returns null.
Limits#
An expression can be at most 4,000 characters (MAX_EXPRESSION_LENGTH) and nest at most 48 levels deep. A function receives at most 256 arguments; further arguments are ignored. Compiled expressions are cached, so repeating the same condition on many fields costs nothing extra.
Using expressions outside a form#
The expression engine is exported, so you can evaluate the same rules on a server, in tests or in your own UI.
evaluateExpression(source, context?)#
Parses (with caching) and evaluates an expression. The context provides the data, an optional scope, custom functions and an error callback:
import { evaluateExpression } from '@birchui/forms';
const claim = { claimType: 'home', estimatedLoss: 12_500, lineItems: [{ amount: 8200 }, { amount: 4300 }] };
evaluateExpression("{claimType} = 'home' and {estimatedLoss} > 10000", { data: claim });
evaluateExpression('sum({lineItems.amount})', { data: claim });The first call returns true and the second 12500. Use this to re-check visibleIf, requiredIf or validator expressions on the server before accepting a submission.
compileExpression(source)#
Compiles once and evaluates many times. The result reports whether parsing succeeded, the errors, and which fields and functions the expression uses:
import { compileExpression } from '@birchui/forms';
const rule = compileExpression('{estimatedLoss} > 5000 and {policeReport} = false');
console.log(rule.ok, rule.variables, rule.functions);
for (const claim of pendingClaims) {
if (rule.evaluate({ data: claim })) flagForReview(claim);
}evaluate() on an expression with syntax errors returns undefined and calls onError.
checkExpression(source, options?)#
Returns diagnostics without evaluating: syntax errors, unknown functions and, when you pass fields, references to fields that do not exist. Each diagnostic has a message, a severity and the start and end character offsets, ready to underline in an editor.
import { checkExpression } from '@birchui/forms';
checkExpression('{estimatedLos} > 5000 and roundup({total})', {
fields: ['estimatedLoss', 'total'],
functions: ['businessDaysBetween'],
});This reports an unknown field estimatedLos as a warning and an unknown function roundup as an error. validateSchema() runs this check for every expression in a schema.
Other exports#
| Export | Purpose |
|---|---|
parseExpression(source) |
The parse result with the syntax tree, errors, variables and functions. |
listFunctionNames(custom?) |
The names of all built-in functions plus your custom ones, for autocompletion. |
BUILTIN_FUNCTIONS |
The built-in function implementations. |
MAX_EXPRESSION_LENGTH |
The maximum expression length. |