15 October 2026
Custom Validation Across Forms and APIs: A TypeScript Guide

TL;DR
For custom validation in a multi-user app, define accepted input and messages in application code, give forms immediate feedback, and enforce the rules again on the server before any write. Select only writable fields, keep authorization separate, and test browser, API, and AI-originated paths against the same contract. The worked example uses db3.ai's @db3.ai/app/validation on the server; the browser uses a lightweight preview of the shared policy.
A form can reject a bad workspace name, but an API client can bypass the form altogether. Even perfectly formatted input cannot establish that a person belongs to the workspace they want to change. We will implement a small workspace-creation contract that rejects unsupported properties and a cross-field inconsistency: requesting member notifications for a private workspace. This is a supporting guide to our application input validation walkthrough, which covers the introductory note example and the library's basic behavior. MDN warns that browser validation cannot be trusted as a server security control, while OWASP recommends checking both input syntax and business semantics. Read MDN's form validation guide and the OWASP Input Validation Cheat Sheet.
Before you start: Have a TypeScript app with the matching preview packages installed according to db3.ai's installation guide, Node.js 24 for the documented walkthroughs, and a browser form or API handler you can edit. Our isolated example needs no database. To run the test, add the vitest, tsx, typescript, and @types/node development dependencies described in the validation service reference. For real writes, you also need authenticated identity, an owner-scoped database operation, and your application's route and response wiring; none is supplied automatically by this example.
Table of contents
- 1. Define one input policy before writing validators
- 2. Validate and select a safe server-side DTO
- 3. Give the form quick feedback without making it authoritative
- 4. Publish actionable errors without leaking submitted data
- 5. Keep permissions and non-browser inputs behind the same boundary
- 6. Test acceptance, rejection, and parity
- 7. Evolve rules without silently breaking clients
- Frequently asked questions
- Put the boundary to work
- Sources
- Recommended Reads
1. Define one input policy before writing validators
Specify what a caller may provide: name is a trimmed string of 3 to 80 JavaScript string units, visibility is private or team, and notifyMembers is an actual JSON boolean. The server supplies ownerId from verified identity. Notification is meaningful only for a team-visible workspace. We keep these constants and the cross-field rule in an application-owned module rather than claiming that the db3.ai validator supports arbitrary callback rules. Its built-in rules check exact top-level keys; they do not strip unknown keys or authorize a caller. The validation guide documents those limits.

Save this file as shared/workspace-policy.ts:
export const workspacePolicy = {
minNameLength: 3,
maxNameLength: 80,
visibility: ['private', 'team'] as const,
} as const;
export type Visibility = (typeof workspacePolicy.visibility)[number];
export function notificationIssue(input: {
visibility: string;
notifyMembers: boolean;
}) {
return input.notifyMembers && input.visibility !== 'team'
? {
field: 'notifyMembers',
code: 'notification_requires_team',
message: 'Choose team visibility before notifying members.',
}
: null;
}
The module is ordinary TypeScript: a browser can use it without importing the backend runtime. A field-level check answers whether each value fits its allowed shape; notificationIssue() answers a question about the combination of two values. Verify this step: a private draft with notifyMembers: true produces an issue, while the same draft with team visibility does not. If a new visibility mode is introduced, update this function and its tests alongside the allowed list.
2. Validate and select a safe server-side DTO
Now use db3.ai's documented validate(input, rules) from @db3.ai/app/validation. The API reference defines its rule objects and return shape; the validation walkthrough explains that result.data is the original object, not a normalized or stripped DTO. That distinction is essential when a request includes an attacker-selected ownerId or an internal flag.
Save the following as server/workspace-input.ts. It expects parsed JSON or a plain object explicitly assembled from form controls, not an arbitrary object with getters. Request-body size limits and parser configuration belong in your HTTP adapter before this function runs, as OWASP's input guidance explains.
import { validate, type ValidationRules } from '@db3.ai/app/validation';
import {
notificationIssue,
workspacePolicy,
type Visibility,
} from '../shared/workspace-policy';
type Issue = { field: string | null; code: string; message: string };
type Draft = { name: string; visibility: Visibility; notifyMembers: boolean };
type Check = { ok: true; value: Draft } | { ok: false; errors: Issue[] };
const rules: ValidationRules = {
name: [
'required', 'string',
{ rule: 'minLength', value: workspacePolicy.minNameLength },
{ rule: 'maxLength', value: workspacePolicy.maxNameLength },
],
visibility: [
'required', 'string',
{ rule: 'in', values: workspacePolicy.visibility },
],
notifyMembers: ['required', 'boolean'],
};
const messages: Record<string, string> = {
'name.required': 'Enter a workspace name.',
'name.string': 'Enter a text workspace name.',
'name.minLength': 'Use at least 3 characters for the name.',
'name.maxLength': 'Use no more than 80 characters for the name.',
'visibility.required': 'Choose a visibility setting.',
'visibility.string': 'Choose private or team visibility.',
'visibility.in': 'Choose private or team visibility.',
'notifyMembers.required': 'Choose whether to notify members.',
'notifyMembers.boolean': 'Choose yes or no for notifications.',
};
export function checkWorkspace(input: unknown): Check {
if (input === null || typeof input !== 'object' ||
Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype) {
return { ok: false, errors: [{
field: null, code: 'invalid_payload', message: 'Send a workspace object.',
}] };
}
const raw = input as Record<string, unknown>;
const allowed = ['name', 'visibility', 'notifyMembers'];
if (Object.keys(raw).some(key => !allowed.includes(key))) {
return { ok: false, errors: [{
field: null, code: 'unexpected_fields', message: 'Remove unsupported fields.',
}] };
}
const candidate = {
name: typeof raw.name === 'string' ? raw.name.trim() : raw.name,
visibility: raw.visibility,
notifyMembers: raw.notifyMembers,
};
const result = validate(candidate, rules);
const errors: Issue[] = result.errors.map(({ field, rule }) => ({
field,
code: `${field}.${rule}`,
message: messages[`${field}.${rule}`] ?? 'Check this field.',
}));
// The library accepts some form strings for 'boolean'; this JSON contract does not.
if (typeof candidate.notifyMembers !== 'boolean' &&
!errors.some(error => error.field === 'notifyMembers')) {
errors.push({ field: 'notifyMembers', code: 'notifyMembers.boolean',
message: messages['notifyMembers.boolean'] });
}
if (errors.length) return { ok: false, errors };
const issue = notificationIssue({
visibility: candidate.visibility as string,
notifyMembers: candidate.notifyMembers as boolean,
});
if (issue) return { ok: false, errors: [issue] };
return { ok: true, value: {
name: candidate.name as string,
visibility: candidate.visibility as Visibility,
notifyMembers: candidate.notifyMembers as boolean,
} };
}
We trim before validating, so the length rule applies to the name we would actually store. We also verify a literal boolean, because the documented boolean rule accepts common form strings without converting them. Only the three explicitly selected properties leave the success branch. Do not call validate() with a TypeScript generic and mistake that annotation for runtime conversion. See the guide's conversion and boolean behavior.
Verify this step: { name: ' Platform ', visibility: 'team', notifyMembers: true } should yield a clean DTO with name: 'Platform'. { name: 'AB', visibility: 'private', notifyMembers: false } fails the minimum; { name: 'Platform', visibility: 'private', notifyMembers: true } fails the cross-field rule; { name: 'Platform', visibility: 'team', notifyMembers: true, ownerId: 'other' } is rejected rather than silently treated as an allowed write. If the result surprises you, inspect whether a library rule accepts a form string or whether normalization occurred on the wrong side of validation.
3. Give the form quick feedback without making it authoritative
Build the form's name length and visibility choices from workspacePolicy; call notificationIssue() when visibility or the notifications checkbox changes. Use required, minlength, and maxlength where appropriate, and display field errors beside their controls. The browser's setCustomValidity() can report a cross-field failure; set it back to an empty string when the user fixes the choice. MDN's Constraint Validation API guide documents that behavior.
A minimal event-handler integration, assuming your existing form provides #workspace-name, #workspace-visibility, and #notify-members controls, is:
import { notificationIssue, workspacePolicy } from '../shared/workspace-policy';
const name = document.querySelector<HTMLInputElement>('#workspace-name');
const visibility = document.querySelector<HTMLSelectElement>('#workspace-visibility');
const notify = document.querySelector<HTMLInputElement>('#notify-members');
if (!name || !visibility || !notify) throw new Error('Workspace form is missing controls.');
name.minLength = workspacePolicy.minNameLength;
name.maxLength = workspacePolicy.maxNameLength;
function preview() {
const trimmed = name.value.trim();
name.setCustomValidity(
trimmed.length < workspacePolicy.minNameLength ||
trimmed.length > workspacePolicy.maxNameLength
? 'Enter a workspace name between 3 and 80 characters.' : '',
);
notify.setCustomValidity(notificationIssue({
visibility: visibility.value,
notifyMembers: notify.checked,
})?.message ?? '');
}
name.addEventListener('input', preview);
visibility.addEventListener('change', preview);
notify.addEventListener('change', preview);
preview();
Render the select options from workspacePolicy.visibility in your UI and use reportValidity() in your existing submit flow if you want the browser to show these messages immediately. The snippet does not include form markup, submission, API error rendering, or a framework-specific component. JavaScript string length and native browser length constraints can differ for some Unicode characters; test representative names in both paths instead of assuming the two implementations are identical. Client-side checks improve the experience, but any client can send a different HTTP body. MDN explicitly cautions against trusting client validation.
Verify this step: switch a private workspace to team while notifications are selected. The notification error should clear. If the form remains invalid after correction, check that setCustomValidity('') ran on the same control. A custom message remains an error until explicitly cleared. MDN documents this requirement.
4. Publish actionable errors without leaking submitted data
On the API boundary, map checkWorkspace() failure to your documented invalid-input status, for example 422 with { code: 'invalid_input', errors }. This is a proposed application response contract, not a promise that the db3.ai runtime registers a route or chooses an HTTP status for you. The generated owned-note JSON API guide uses its own Fastify schemas and HTTP error policy, so adapt that route rather than pasting this function into a fictitious automatic endpoint.

A field error might be { "field": "notifyMembers", "code": "notification_requires_team", "message": "Choose team visibility before notifying members." }. An unsupported property or malformed object is a form-level error with field: null; unexpected server and database failures need a distinct generic response and private diagnostic record, not a validation message. When rendering API failures, match codes to form controls and use a form-wide alert for field: null. Keep status, codes, and messages stable enough that older clients can respond sensibly.
Do not return the library's raw failures. The documented ValidationFailure may include the original value and details, which can expose credentials, private text, or unexpected data. Our mapper emits only controlled field names, codes, and messages. If your UI needs localization, translate stable codes in the client; do not make clients parse English messages. The error shape and warning appear in db3.ai's validation documentation.
Verify this step: send an unsupported property with a recognizable secret value, then confirm neither response nor request logs repeat the key's value. A useful error says what to fix without echoing a submitted password, token, or raw tool argument. OWASP also recommends excluding sensitive rejected input from logs. See OWASP's guidance.
5. Keep permissions and non-browser inputs behind the same boundary
After the input passes, authenticate the caller, derive the owner or tenant from trusted server context, authorize the requested operation, and persist the selected DTO. Neither visibility: 'team' nor an ownerId that happens to look valid proves membership. Our owned-note API example demonstrates querying by both record ID and authenticated owner when accessing an existing private note. OWASP's object-level authorization guidance explains why the separate policy matters.
The same checkWorkspace(unknown) function can run before a service processes an import, queued payload, or AI-generated proposal. Do not assume structured model output establishes the user's permission or a business rule: db3.ai's structured-output example says schema validation establishes shape, not factual or domain correctness. For an agent that proposes a new workspace, pass only its proposed writable fields through this checker; obtain the actor and tenant from the application context and recheck the relevant permission before the actual side effect. If work is queued, decide what happens if membership changes between dispatch and execution.
Verify this step: test one authorized user and one unrelated user attempting the same operation with an otherwise valid body. Only the authorized path may write. If both succeed, improving the name validator will not solve the missing authorization check. Do not assume that a browser preview, a valid schema, or a previous authorization at queue time is sufficient for a later worker action.
6. Test acceptance, rejection, and parity
Save the following as tests/workspace-input.test.ts if shared/ and server/ are siblings of tests/. It tests application logic with the documented vitest runner; it does not test a live HTTP route, browser DOM, database, or permissions. The db3.ai validation walkthrough demonstrates testing the installed package in an independent app.
import { expect, it } from 'vitest';
import { checkWorkspace } from '../server/workspace-input';
it('normalizes and selects an allowed workspace draft', () => {
expect(checkWorkspace({
name: ' Platform ', visibility: 'team', notifyMembers: true,
})).toEqual({ ok: true, value: {
name: 'Platform', visibility: 'team', notifyMembers: true,
} });
});
it('rejects edge cases and unsafe fields without reflecting values', () => {
for (const input of [
null, [], {},
{ name: ' ', visibility: 'team', notifyMembers: true },
{ name: 'A'.repeat(81), visibility: 'team', notifyMembers: false },
{ name: 'Plan', visibility: 'public', notifyMembers: false },
{ name: 'Plan', visibility: 'team', notifyMembers: 'yes' },
{ name: 'Plan', visibility: 'private', notifyMembers: true },
{ name: 'Plan', visibility: 'team', notifyMembers: false,
ownerId: 'SECRET_OWNER_MARKER' },
]) {
const checked = checkWorkspace(input);
expect(checked.ok).toBe(false);
expect(JSON.stringify(checked)).not.toContain('SECRET_OWNER_MARKER');
}
});
From the application root, run npx vitest run tests/workspace-input.test.ts and your project's TypeScript check after installing the matching packages and test dependencies. These are instructions and expected checks, not a claim that we executed the example here. If imports fail, confirm the documented preview installation and the folder layout; if the browser disagrees with the test, inspect its rendered select choices, normalization timing, and Unicode length behavior.
Next, exercise your real form submission and HTTP handler with the same valid and invalid cases. Add tests that verify 422 (or your chosen invalid-input status), no write on failure, 401 for a missing session, and a denial for another user's record. Run those against a disposable database and the real authentication adapter where relevant. Our owned-note API guide distinguishes isolated input checks from authenticated HTTP and persistence tests.
7. Evolve rules without silently breaking clients
When product requirements change, update the policy, server rule mapping, form options, and parity fixtures in the same change. Changing visibility from two choices to three may alter the cross-field meaning of notifications; simply adding a select option is not enough. Preserve stable error codes where the meaning stays the same, and document intentional changes when older clients may submit a value the server no longer accepts.
A database uniqueness constraint is still useful for a name or slug that must be unique, but a preflight lookup cannot guarantee uniqueness under concurrent writes. Let the database arbitrate races, then map a known conflict to a safe response. Keep field conversion in the owning model when using ActiveRecord; the db3.ai field and request-mapping guide and validation reference distinguish model conversion from earlier request checks. This plain-object example does not install those model policies or migrations for you.
Verify this step: replay an old client payload and a newly allowed payload against the revised boundary. Confirm the form and API agree on the changed case, the forbidden owner field remains forbidden, and database conflicts do not become success responses. If the old client breaks, version or stage the contract change rather than just rewriting the display message.
Frequently asked questions
Is custom validation the same as authorization?
No. Validation decides whether a proposed payload meets its input contract; authorization decides whether an authenticated actor may perform an operation on a specific resource. A valid workspace name cannot grant access to another user's workspace. OWASP distinguishes the checks.
Can I reuse the db3.ai validator directly in browser code?
The documented import and examples establish its server-side use but do not establish a browser-bundle contract. We share an application-owned policy module with the form and enforce the full rule set at the server. If your build supports sharing more code, verify that specific package version and browser bundle before depending on it. Review the supported validation import and package installation notes.
Put the boundary to work
You now have a selected workspace DTO, controlled errors, a browser preview, and tests for the rule itself. The next useful action is to wire checkWorkspace() into your authenticated creation handler, then prove with two users that a valid payload cannot cross an ownership boundary. Start from our owned-note JSON API walkthrough for the wider route, identity, and persistence pattern, or consult the validation API reference for the exact exported contracts.
Sources
- db3.ai validation guide
- db3.ai validation API reference
- db3.ai validation service reference
- db3.ai installation guide
- db3.ai owned-note JSON API guide
- db3.ai ActiveRecord guide
- db3.ai structured-output guide
- MDN client-side form validation
- MDN Constraint Validation API
- OWASP Input Validation Cheat Sheet
- OWASP API1:2023 Broken Object Level Authorization
Recommended Reads
- How to Create TypeScript APIs With Clear Boundaries, Authentication, and Tests: Extend the input contract into an authenticated, tested API.
- 4 TypeScript Authentication Frameworks Compared: Sessions, Permissions, and Backend Fit: Compare identity and session choices before designing resource policies.
- How to Build AI Products That Work in Production: Review the data and action boundaries around machine-generated inputs.