@figentra/validation bridges that gap by letting you declare schemas that both validate data at runtime and drive TypeScript’s inference of the resulting types, so you never have to maintain a separate type definition alongside your validation logic.
Installation
Defining a Schema
Useschema to compose a reusable validation schema from typed field builders. Define schemas at module scope so they are created once and reused across validation calls.
Validating Input
Pass any unknown value tovalidate along with your schema. The result is a discriminated union — check result.success to branch between the valid and invalid paths.
result.data is narrowed to the inferred schema type. When it fails, result.errors contains a structured list of every field-level problem found — not just the first one.
TypeScript Inference
schema() builds its TypeScript type from the field declarations you provide. Use the InferSchema utility type to extract that type for use in function signatures, interfaces, or other type definitions — without duplicating your schema structure.
- With InferSchema
- Without InferSchema
Validation Error Format
Whenresult.success is false, result.errors is an array of field-level error objects. Every error identifies the offending field and provides a human-readable message suitable for returning to an API client.
validate surfaces every problem at once rather than stopping at the first failure.
Field Builders
string(options)
Validates string values. Supports
minLength, maxLength, pattern (regex), and optional.number(options)
Validates numeric values. Supports
min, max, integer (whole numbers only), and optional.email()
Validates that the value is a well-formed email address. Accepts no additional options.
boolean()
Validates strict boolean
true / false values. Use @figentra/config’s boolean field for environment variable coercion.url(options)
Validates that the value is a well-formed URL. Supports
protocols to restrict allowed URL schemes and optional.array(itemSchema, options)
Validates an array of items, where each item is validated against
itemSchema. Supports minLength and maxLength.Integration with @figentra/error
result.errors is designed to flow directly into the ValidationError constructor from @figentra/error. The error class expects the same array structure, so no mapping or transformation is required.
ValidationError is caught by your error-handling middleware, which serialises the field-level errors into the response body without any additional work.
Complete Example
The following example shows a fully typed request handler for a user registration endpoint, from schema definition through to the service call.schemas/user.ts
handlers/createUser.ts