Validating in the middle of a program
To check a value partway through a program, construct it. Type(value)
checks every rule on the type and the types it builds on, and an
attempt maps each rule that can break to the failure the caller gets
(Construction failures by rule).
That holds wherever the value came from: a computation, a part of a
request, a cell of an import, or json.read.
For one value, name the rule that can break:
var quantity: Quantity = attempt Quantity(line.count * 2) { max: OrderTooLarge}
For a whole record, build each part first, as its field's type. The object literal then can't fail (Objects):
var name: Badge.name = attempt Badge.name(text.trim(profile.display_name)) { max_length: BadgeNameTooLong}return Badge { name: name colour: profile.colour}
For data that arrives as text, json.read decodes it and checks every
field rule of the type in one step, so there is no second validation:
var order: OrderImport = attempt json.read(message.body, as: OrderImport) { malformed: ImportUnreadable mismatch: ImportInvalid}
A rule across fields, such as "ends after it starts", is a named rule on the object type (Rules across fields), checked by the same construction.
Markdown for agents: /docs/validating-in-the-middle-of-a-program.md.Built from Jadpo main at a707efb.