Expressions
Every total, condition and rule in this quote is written as text: {Quantity} * {UnitPrice},
{Total} >= 10000, {ValidUntil} > {IssuedOn}. Text travels - it is exported
to JSON Schema and imported back - so a form a server sends can compute, decide and judge with no code
behind it. An expression reads the answers and calls a fixed list of functions, and nothing else.
Answer
0
View source
@page "/expressions"
<BormView State="_state" OnValidSubmit="HandleSubmit" SubmitText="Send quote" />
@code {
private readonly Quote _model = new() { IssuedOn = DateOnly.FromDateTime(DateTime.Today) };
private BormState _state = default!;
protected override void OnInitialized()
{
var schema = BormBuilder.For<Quote>()
.Title("Quote")
.Field(x => x.Customer, f => f.Required())
.Field(x => x.CustomerType, f => f.AsRadio().Options(("person", "Person"), ("company", "Company")))
.Field(x => x.VatNumber, f => f
.VisibleWhen("{CustomerType} = 'company'")
.RequiredWhen("{CustomerType} = 'company'")
.Must("matches({VatNumber}, '^[A-Z]{2}[0-9A-Z]{8,12}$')",
"Two letters, then 8 to 12 letters or digits."))
.Array(x => x.Lines, line => line
.Field(l => l.Product, f => f.Required())
.Field(l => l.Quantity, f => f.Must("{Quantity} >= 1", "Order at least one."))
.Field(l => l.UnitPrice, f => f.Step(0.01).Must("{UnitPrice} > 0", "Give the line a price."))
// This row's quantity and price: a path resolves against the row first.
.Computed(l => l.LineTotal, "{Quantity} * {UnitPrice}"),
f => f.Attr("itemNoun", "line"))
.Field(x => x.Discount, f => f.Must("{Discount} <= sum({Lines[].LineTotal})",
"The discount cannot be more than the lines."))
// [] is every row. A missing discount is no discount.
.Computed(x => x.Total, "round(sum({Lines[].LineTotal}) - coalesce({Discount}, 0), 2)")
.Field(x => x.Approver, f => f
.VisibleWhen("{Total} >= 10000")
.RequiredWhen("{Total} >= 10000")
.Help("A quote of 10,000 or more needs an approver."))
.Field(x => x.IssuedOn, f => f.Required())
.Field(x => x.ValidUntil, f => f
.Must("{ValidUntil} > {IssuedOn}", "A quote is valid until some day after it is issued.")
.Must("dateDiff({IssuedOn}, {ValidUntil}) <= 90",
"More than 90 days is unusual - check with finance.", BormValidationSeverity.Warning))
.MustAll("count({Lines}) > 0", "Add at least one line.", nameof(Quote.Lines))
.Build();
_state = new BormState(schema, new BormModelDataAccessor(_model));
}
public void Dispose() => _state.Dispose();
}The language
- Fields are written in braces:
{Email},{Address.City},{Lines[0].Product}. A path resolves against the object that owns the field first, so on a repeater's row{Quantity}is that row's.[]means every row:{Lines[].LineTotal}is the list of every line's total. - Values: numbers (
12,0.5,1e3), text in single or double quotes,true,false,null, and lists['a', 'b']. - Operators:
+ - * / %,=(or==),!=(or<>),< <= > >=,in,not in,and(&&),or(||),not(!). Comparisons do not chain: write1 < {x} and {x} < 5. - Numbers are decimals, so
0.1 + 0.2is0.3and money adds up. Text joins with+; text compares without regard to case. A date plus a number moves it by that many days, and one date minus another is the days between them. - A missing answer reads as
null. A comparison that needs one is unknown: a condition that is unknown is false, so a field depending on a missing answer stays hidden, and a rule that is unknown passes - saying a value is missing isRequired()'s job. Dividing by zero is no answer, not an error.
| Kind | Functions |
|---|---|
| Logic | iif(condition, then, else), coalesce(a, b, …), isEmpty(x), isNotEmpty(x) |
| Text | len / length (a list's count too), lower, upper, trim, concat(…), substring(text, start, length?), contains, startsWith, endsWith, matches(text, 'pattern') |
| Numbers | abs, round(x, digits?), floor, ceil, number(x), text(x) |
| Aggregates | sum, avg, min, max, count - each takes values, lists or both, and skips what has not been answered |
| Dates | today(), now(), year, month, day, age(birthDate), dateDiff(from, to, unit?) ('days', 'weeks', 'months', 'years', 'hours', 'minutes'), addDays, addMonths, addYears |
Where an expression goes
| In C# | In JSON Schema | Means |
|---|---|---|
VisibleWhen, RequiredWhen, DisabledWhen, ReadOnlyWhen, a step's VisibleWhen | x-visibleWhen, x-requiredWhen, …, a step's visibleWhen | A condition. |
Computed("{Quantity} * {UnitPrice}") | x-computed | A value derived from others, read-only by default. |
Must(expression, message, severity) | x-rules | A rule on one field. It revalidates whenever a field it reads changes. |
MustAll(expression, message, field) | x-rules on the root | A rule on the whole form, its message put on field. |
When(expression, w => …) | - | Rules that apply only while it holds. |
The fields an expression reads are its dependencies, so it is evaluated again exactly when one of them changes -
there is no dependsOn to keep in step. Expressions are synchronous and pure: a rule that calls a
service stays a delegate (MustAsync, OptionsFrom) and works alongside them.
Safe to take from anyone - and functions of your own
An expression is not a program. It reads the form's values and calls the functions above, and nothing else: no member
access, no reflection, no assignment, no loops - so one from an untrusted document always finishes and can read nothing
but the answers. Parsing is bounded (4,096 characters, 48 levels of nesting, 1,024 parts), matches takes its
pattern only as a literal and with a time limit, and evaluating never throws. An expression that does not parse fails
the import, naming the field, rather than being dropped.
Registered functions are the trust boundary: an expression from any document can call them, so register only what is
safe with any argument. This site registers vatRate at startup - try it in the console above:
BormExpressionFunctions.Register("vatRate", args => args[0] is string country ? country.ToUpperInvariant() switch { "NL" => 0.21m, "DE" => 0.19m, "FR" or "GB" => 0.20m, _ => null } : null, minArgs: 1, maxArgs: 1); // "x-computed": "round({net} * (1 + vatRate({country})), 2)"
today() and now() read BormExpressionFunctions.TimeProvider, which a test can replace
with a fixed clock. BormExpression.TryParse and Evaluate - what the console uses - run one on its own.