Validate models
Check models and data, show field errors in a form, and read the errors that golem reports.
Validation checks a value against the validation tags on the field types of a model. Golem generates the checks. They run when you call a validation function and when you convert JSON (Serialization). Constructors and field assignments do not run them, so you can keep an incomplete model while someone edits it.
failFast is an option of the validation calls. A call stops at the first issue by default. Pass { failFast: false } to collect every issue, for example to show all field errors in a form.
The examples use a task form. Its title must not be blank. MinLength<1> rejects an empty string, and the custom rule TValidation<typeof notBlank> also rejects a title of spaces (Validation tags).
import type { MinLength, TValidation } from '@exprtlabs/golem/tags';
export function notBlank(value: string): boolean | string {
return value.trim().length > 0 || 'Enter a title.';
}
export type TaskTitle = string & MinLength<1> & TValidation<typeof notBlank>;import { model, type IModel } from '@exprtlabs/golem/model';
import type { TaskTitle } from './task-input-rule.js';
export type TTaskInput = IModel<{
title: TaskTitle;
done: boolean;
}>;
export class TaskInput extends model<TTaskInput>() {}import { validateInstance } from '@exprtlabs/golem/validation';
import { TaskInput } from './task-input.model.js';
export async function checkTaskInput() {
const task = new TaskInput({ title: ' ', done: false });
const blank = await validateInstance(task);
task.title = 'Write release notes';
const fixed = await validateInstance(task);
// -> { blank: ['Enter a title.'], fixed: true }
return { blank: blank.map(issue => issue.message), fixed: fixed.length === 0 };
}validation defaults to true. It also takes false and 'sanity', which checks the shape only. IObject and IModel accept { validation: true | false | 'sanity' } to set the default level of that declaration. The level is at or below the project level.
The calls
| Call | Returns | Stops at the first issue | Throws |
|---|---|---|---|
validateInstance(model) | A promise of the issue list, empty when the model is valid | Yes. { failFast: false } returns every issue. | Nothing for an invalid value. LibError when validation cannot run. |
getValidator(model).validate() | A promise of true or false. It stores the field errors on the validator. | Yes. { failFast: false } stores every field error. | Nothing for an invalid value. LibError when validation cannot run. |
validate<T>(value) | true or false, and narrows value to T | Yes. { failFast: false } does not change the result. | Nothing for an invalid value. LibError when validation cannot run or no build rewrote the call. |
assertValue<T>(value) | The value, typed as T | Yes. { failFast: false } puts every issue in the error. | LibError of kind validation with the issues when the value is invalid. |
Choose a check
| Task | Call |
|---|---|
| Check a model you built | validateInstance(model) |
| Show field errors in a form | getValidator(model) |
| Check untrusted data against a type | validate<T>(value) (type predicate) |
| Check while converting | the default in parse and fromWireFormat (Serialization) |
| Check the shape only | validate: 'sanity' (Choose a level for one call) |
Check @Body() and @Query() in NestJS | NestModelInterceptor (NestJS requests) |
| Call an API | a generated client validates the request and response (Call operations) |
Choose a level for one call
A call checks at the default level of its model. Pass validate to choose another level for one call.
import { parse } from '@exprtlabs/golem/serde';
import { validate } from '@exprtlabs/golem/validation';
import { TaskInput } from './task-input.model.js';
export function readTaskShape(text: string) {
// The shape only: a blank title passes. A missing key or a wrong type throws.
return parse<TaskInput>(text, { validate: 'sanity' });
}
export function hasTaskShape(value: unknown) {
return validate<TaskInput>(value, { validate: 'sanity' });
}| Call | validate takes |
|---|---|
parse<T>, stringify<T>, fromWireFormat<T>, toWireFormat<T> | true, 'sanity' or false |
validate<T>, assertValue<T>, validateInstance, getValidator(model).validate | true or 'sanity' |
- Without
validate, the call uses the default level of its model. The model level is only a default. - A call can choose any level up to the project level. Off is always allowed.
- A level above the project level throws a
LibErrorof kindValidationUnavailable, because golem wrote no validators for it. - For
parse,stringify,fromWireFormatandtoWireFormat, any other value throws aTypeError.validateInstanceandgetValidator(model).validatethrow it too. - A nested model is checked at the level of the call that reaches it.
The table shows the level of a call that names validate. Only the conversion calls take false.
| Project level | validate: true | validate: 'sanity' | validate: false |
|---|---|---|---|
true | Full check | Shape only | No check |
'sanity' | ValidationUnavailable | Shape only | No check |
false | ValidationUnavailable | ValidationUnavailable | No check |
A model with { validation: false } has no validators. A call cannot check it, at any project level.
A call at 'sanity' skips the instance rules that you add with extend().
Validate a model
validateInstance(task) returns the issues of the task. The check above reports one issue for the blank title and none once the title is fixed. Use getValidator(model) when a form needs the errors of each field.
Stored validation state
getValidator(model) returns the cached stateful validator for editor flows. Its type uses the generated declared fields. Methods and other properties that only your class adds are not validation fields.
| Property or method | Does |
|---|---|
await getValidator(model).validate() | Returns true or false and replaces stored errors with the current results. Pass { failFast: false } to store every field error. |
error('title') | The first message for a field, or undefined. |
errorsFor('title') | All messages for that field. |
issues | Structured errors with paths, codes, sources, messages and the fields of each code, such as limit on a tooSmall issue. |
errors | A map from each field's escaped path to its messages. |
pending | Whether validation is in progress. |
valid | Whether the stored issues are empty. It does not track unvalidated edits. |
clear() | Removes the stored issues and resets pending. |
setErrors(map) | Stores messages from outside generated or instance rules, such as a server response. |
extend(rules) | Adds a rule for this model instance, including asynchronous checks. |
messages(overrides) | Overrides the message for a generated check, by field and code, such as 'title.tooSmall'. |
Changing a field does not clear its old error. Validate again to refresh the result, or call clear() to remove the stored errors.
Nested field errors
Pass a path array to read errors inside objects or arrays. Field names are strings. Array indexes are numbers.
import { model, type IModel } from '@exprtlabs/golem/model';
import type { MinLength } from '@exprtlabs/golem/tags';
import { getValidator, validateInstance } from '@exprtlabs/golem/validation';
export type TChecklistInput = IModel<{
items: Array<{ label: string & MinLength<3> }>;
}>;
export class ChecklistInput extends model<TChecklistInput>() {}
export async function checkChecklistInput() {
const checklist = new ChecklistInput({ items: [{ label: 'x' }] });
const issues = await validateInstance(checklist);
const validator = getValidator(checklist);
await validator.validate();
const labelError = validator.error(['items', 0, 'label']);
checklist.items = [{ label: 'Tag' }];
const fixedCount = (await validateInstance(checklist)).length;
// -> { firstIssuePath: ['items', 0, 'label'], labelError: 'Must be at least 3 characters', fixedCount: 0 }
return { firstIssuePath: issues[0]?.path, labelError, fixedCount };
}Use issues when you need the code or source of an error as well as its message. The errors map keys messages by escaped JSON Pointer.
Instance rules
Use extend() for a rule added to a particular model, including asynchronous checks. The callback receives the field value and the model, and returns true or an error message, directly or through a promise.
import { TaskInput } from './task-input.model.js';
import { getValidator } from '@exprtlabs/golem/validation';
export async function checkTitleRule() {
const task = new TaskInput({ title: 'Write release notes', done: false });
const validator = getValidator(task);
validator.extend({
title: value => value.startsWith('Ship') || 'Start the title with Ship.',
});
const valid = await validator.validate();
// -> { valid: false, message: 'Start the title with Ship.' }
return { valid, message: validator.error('title') };
}- Generated checks run before instance rules. A rule that throws on a field the generated checks already rejected is skipped, and the generated issue stands.
- Register the rule in your class constructor when every instance needs it, including instances created by
fromWireFormat<TaskInput>(). - Use
TValidationfor a reusable synchronous predicate attached to a field type.
Errors from an API
setErrors() lets you display a server message beside local validation errors. It stores messages and does not add validation rules.
import { TaskInput } from './task-input.model.js';
import { getValidator } from '@exprtlabs/golem/validation';
export function checkServerErrors() {
const task = new TaskInput({ title: 'Write release notes', done: false });
const validator = getValidator(task);
validator.setErrors({ title: 'This title is already used.' });
const beforeClear = validator.error('title');
validator.clear();
const afterClear = validator.error('title');
// -> { beforeClear: 'This title is already used.', afterClear: undefined }
return { beforeClear, afterClear };
}The next validator.validate() replaces these messages with its own results. The standalone validateInstance(task) leaves them unchanged. To customize messages for generated checks, use messages() with the code of the issue, such as tooSmall.
Errors and issues
- An invalid value is an ordinary result for
validateInstanceandvalidate(). - A call that converts a value throws a
LibErrorinstead:parse,stringify,fromWireFormat,toWireFormatandassertValue. - A validator also throws
LibErrorwhen validation cannot run, for example when the model was generated withvalidation: false, or when a call asks for a level above the project level. - A validator throws
LibErrorwhen a rule or a converter throws.
import { LibError, LibErrorKind } from '@exprtlabs/golem/errors';
import { parse } from '@exprtlabs/golem/serde';
import { Task } from './task.model.js';
export function explainTaskText(text: string): string[] {
try {
parse<Task>(text, { failFast: false });
return [];
} catch (error) {
if (!(error instanceof LibError) || !error.causedByInput) throw error; // a program fault
if (error.kind === LibErrorKind.InvalidJson) return ['The text is not JSON.'];
return error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`);
}
}A LibError from @exprtlabs/golem/errors has these members:
| Member | Holds |
|---|---|
kind | the failure category: validation, invalid_json, serialization, deserialization, validation_unavailable or response |
issues | a frozen list of failed checks |
causedByInput | true when the rejected value is at fault, such as a failed check or a Deserialize function that throws on wire input. false for a program fault |
cause | the exception that a LibError wraps, if any |
Each issue has a code, a path, a message and a source. Check issue.code and TypeScript narrows to the fields of that code, such as issue.limit after issue.code === 'tooSmall'. A path such as ['items', 0, 'amount'] names the field. Every kind, code and field is in the runtime reference.
Constraints on the models of a NestJS controller reach the OpenAPI document that golem writes. Constraints in an OpenAPI document reach the generated validators and clients. The tag-to-keyword mapping is in Model schemas, and the supported keywords are in OpenAPI support.
Translate messages
Translate validation and input errors into your user's language with any t(key, options) function, such as i18next. Golem maps each issue to a field key (<Declaration>.<field>.<code>) and a shared key (golem.<code>), passes interpolation variables such as limit, count, pattern and expected, and falls back to English when a key is missing.
Browser setup
Register one translator at start-up with setIssueTranslator from @exprtlabs/golem/errors. Every parse, fromWireFormat, validateInstance and ModelValidator.validate call formats its issues through it.
import { setIssueTranslator, type IssueTranslate } from '@exprtlabs/golem/errors';
declare const i18next: { readonly t: IssueTranslate };
export function installBrowserTranslator(): void {
setIssueTranslator((key, options) => i18next.t(key, options));
}Pass setIssueTranslator(undefined) to restore the default English messages.
Server per-request translation
Do not install a global translator on a multi-locale server. Catch LibError and pass error.issues and the request's translator to translateIssues:
import { LibError, translateIssues, type Issue } from '@exprtlabs/golem/errors';
import { parse } from '@exprtlabs/golem/serde';
import { TaskInput } from './task-input.model.js';
export function parseTaskForRequest(
body: string,
request: { readonly t: IssueTranslate },
): { readonly ok: true; readonly value: TaskInput } | { readonly ok: false; readonly issues: readonly Issue[] } {
try {
return { ok: true, value: parse<TaskInput>(body, { failFast: false }) };
} catch (error) {
if (error instanceof LibError && error.causedByInput) {
return { ok: false, issues: translateIssues(error.issues, request.t) };
}
throw error;
}
}Generate a scan file for key extractors
Enable model.issueMessages in golem.yaml so generated validators stamp field owners (<Declaration>.<field>) and golem writes a scan-only TypeScript file for i18n extractors such as i18next-cli:
version: 1
model:
issueMessages:
function: t
output: src/i18n/issue-messages.generated.tsBy default, golem writes the scan file to .golem/models/issue-messages.generated.ts. Set output inside src/ when your extractor skips dotfiles such as .golem/. Do not import the scan file at run time.
Precedence order
Golem resolves each issue message in this order:
- Explicit messages stay unchanged:
setErrors()external messages,ModelValidator.messages()overrides,TValidationstring reasons andextend()rule reasons. - Field key:
<Declaration>.<field>.<code>(whenmodel.issueMessagesis enabled). - Shared key:
golem.<code>(with sub-keys such asgolem.tooSmall.length.inclusiveand pluralcount). - Default English text.
Full example: examples/models.
