Skip to content
LykosJSLYKOSJS
CreatorDeveloperBenchmarkshomeGet started
v1.0.0
Application & serverREST APIGraphQLRouting & groupsRequest context & repliesValidationError handling
PREVIOUSRequest context & repliesNEXT Error handling
© 2026 LykosJS · MIT LicenseBun · TypeScript

© 2026 LykosJS. Released under the MIT License.
Built by Zen Allaham.

DocsGitHubX
DOCS/V1.0.0/CORE CONCEPTS
CORE CONCEPTS

Validation

Build reusable, strongly typed validation schemas with LykosJS. Validate untrusted data, infer TypeScript types, normalize values and handle validation errors with a fluent API.

LykosJS command-line interface

Introduction

LykosJS provides a fluent validation API for defining reusable schemas and validating untrusted data at runtime. Each schema describes the expected shape of an object, the type of every field, its presence requirements and the rules that its value must satisfy.

The Validator API is designed around two things: runtime validation and compile-time type safety. TypeScript IntelliSense only exposes rules that are valid for the selected field type and its current configuration. After successful validation, the returned data type is inferred directly from the schema.

Import the validation API

ts
1import { defineSchema, InferSchema, Validator } from 'lykosjs'

Validator provides field builders and validation methods. defineSchema() checks schema definitions at compile time, while InferSchema extracts the corresponding TypeScript data type.

Define your first schema

ts
1import { defineSchema, Validator } from 'lykosjs'2 3export const CreateUserRule = defineSchema({4  name: Validator.string(2, 50).required(),5  email: Validator.text().required().email().trim().lowercase(),6  age: Validator.number(18, 120).optional(),7  website: Validator.text().url().nullable(),8})

Each property represents a field, and its value must be a validator created through Validator. The factory selects the field type (and, for string(), number() and array(), can also receive the limits directly). The chain of methods that follows defines the field's presence and validation rules.

  • name is a required string containing between 2 and 50 characters.
  • email is a required text value that must be a valid email address. It is trimmed and converted to lowercase.
  • age is an optional finite number between 18 and 120.
  • website may be omitted or contain null. When provided as a value, it must be a valid HTTP or HTTPS URL.

Field presence rules

Every field must explicitly choose one presence rule before it can be used in a schema. A fresh validator starts without a presence rule, and TypeScript will prevent it from being used in defineSchema() (or in Validator.validate() and Validator.object()) until one is selected.

required()

Marks a field as mandatory. The property must exist and its value cannot be undefined, null or an empty string containing only whitespace.

ts
1const LoginRule = defineSchema({2  email: Validator.text().required(),3  password: Validator.string(8, 100).required(),4})

A required field cannot be omitted or supplied as null. Required text fields also reject blank strings such as "" and " ". The error message is <field> is required.

nullable()

Allows a field to be omitted or explicitly set to null. If a non-null value is provided, its normal type and validation rules still apply.

ts
1const ProfileRule = defineSchema({2  bio: Validator.text().nullable(),3  website: Validator.text().url().nullable(),4})

Nullable fields are optional in the inferred TypeScript type and include null in their value type.

optional()

Allows a field to be omitted or set to undefined. When a value is provided, it must satisfy the field's type and validation rules. Unlike nullable(), this rule does not allow null: a null value is validated like any other value and fails the type check.

ts
1const UpdateUserRule = defineSchema({2  displayName: Validator.text().minLength(2).optional(),3  age: Validator.number(18, 120).optional(),4})
Choose exactly one presence rule
Do not combine required(), nullable() and optional() on the same field. They are mutually exclusive. TypeScript prevents the invalid combinations in normal usage, and the schema compiler rejects them at runtime with a TypeError. Calling the same presence rule twice is also rejected.

How presence affects TypeScript

The inferred type distinguishes required properties from nullable and optional properties. This affects both whether a property must exist and which values it can contain.

ts
1const UserRule = defineSchema({2  name: Validator.text().required(),3  bio: Validator.text().nullable(),4  nickname: Validator.text().optional(),5})6 7type User = InferSchema<typeof UserRule>8 9// Equivalent inferred type:10type User = {11  name: string12  bio?: string | null13  nickname?: string14}
  • required() produces a mandatory property.
  • nullable() produces an optional property whose value can also be null.
  • optional() produces an optional property without adding null to its value type.

Validator field builders

Every field starts with a factory method on Validator. The selected factory determines the field's TypeScript value type and which validation rules are available.

  • Validator.string(minLength, maxLength) — a string with a mandatory length range.
  • Validator.text() — a string without predefined limits.
  • Validator.number() or Validator.number(min, max) — a finite number.
  • Validator.boolean() — a boolean.
  • Validator.array() or Validator.array(minItems, maxItems) — an array.
  • Validator.enum(options) — a fixed set of string values.
  • Validator.date() — a date.
  • Validator.object(shape) — a nested object.

String fields

Use Validator.string(minLength, maxLength) to create a string validator with mandatory minimum and maximum length arguments.

ts
1const UsernameRule = defineSchema({2  username: Validator.string(3, 24).required(),3})

Both limits are applied as length checks. The factory already defines these two rules, so minLength() and maxLength() are not available on the same builder.

String validators additionally support email(), url(), confirmed(), trim() and lowercase().

Text fields

Use Validator.text() when you want a string without predefined length limits. You can add length rules as needed with minLength() and maxLength().

ts
1const DescriptionRule = defineSchema({2  description: Validator.text().minLength(10).maxLength(500).trim().required(),3})

Both string() and text() validate JavaScript string values. Neither automatically converts numbers or other values into strings.

Number fields

Use Validator.number() to validate finite JavaScript numbers (NaN and Infinity are rejected). You can pass the minimum and maximum values to the factory, or create the validator without arguments and chain min() and max().

ts
1const ProductRule = defineSchema({2  price: Validator.number().min(0).required(),3  quantity: Validator.number(1, 1000).required(),4})

You can create a number validator with no arguments, or provide both minimum and maximum values. Providing only one argument is invalid, both for TypeScript and at runtime. When the range is passed to the factory, min() and max() are no longer available on that builder.

ts
1// Correct2Validator.number()3Validator.number().min(1).required()4Validator.number(1, 100).required()5 6// Incorrect7Validator.number(1)8Validator.number(1, 100).min(5)
Numbers are not automatically converted
A JSON value such as "25" is a string, not a number. Validator.number() does not convert it to 25. The value must already be a finite JavaScript number.

Boolean fields

Use Validator.boolean() for boolean values. No additional value rules are currently exposed for this field type.

ts
1const SettingsRule = defineSchema({2  notifications: Validator.boolean().required(),3  marketing: Validator.boolean().optional(),4})

Only actual true and false values pass. Strings such as "true" and numbers such as 1 are not converted.

Array fields

Use Validator.array() to validate arrays. You can optionally specify both minimum and maximum item counts, either as factory arguments or by chaining minItems() and maxItems() on an array created without arguments.

ts
1const TagsRule = defineSchema({2  tags: Validator.array().minItems(1).maxItems(10).required(),3  attachments: Validator.array(0, 5).optional(),4})

The array validator checks that the value is an array and can enforce its item count. Its inferred value type is unknown[]. It does not currently define a nested element validator through the array builder. As with numbers, providing only one argument to Validator.array() is invalid.

Array elements remain unknown
Validator.array() does not validate the type or structure of individual array elements. If your application needs to validate every item, you must perform that additional validation separately.

Enum fields

Use Validator.enum() to restrict a field to a fixed collection of string values. It accepts a non-empty array, a string enum or a comma-separated string.

ts
1const RoleRule = defineSchema({2  role: Validator.enum([3    'admin',4    'user',5    'moderator',6  ]).required(),7})

When an array is provided, TypeScript infers the exact union of its values.

ts
1type Role = 'admin' | 'user' | 'moderator'

A string enum or a readonly object of string values can also be used. A comma-separated string is accepted too, but its inferred type is just string.

ts
1enum UserRole {2  Admin = 'admin',3  User = 'user',4}5 6const UserRule = defineSchema({7  role: Validator.enum(UserRole).required(),8})9 10const StatusRule = defineSchema({11  status: Validator.enum('draft,published,archived').required(),12})

Comma-separated input is trimmed around each option, but the accepted values are compared strictly and case-sensitively. Empty options and duplicate options are rejected when the validator is created.

ts
1// Accepted2'admin'3'published'4 5// Rejected6'Admin'7' administrator '8'unknown'

A value outside the list produces the message <field> must be one of: a, b, c.

Enum values are strings
Enum validation does not coerce values. Numeric enum values and non-string options are not supported by this API.

Date fields

Use Validator.date() to validate dates. Successful validation always returns a JavaScript Date object, even when the original input was an ISO date string.

ts
1const EventRule = defineSchema({2  eventDate: Validator.date().required(),3})

The date validator accepts valid Date instances and strict ISO 8601 strings. It rejects numbers, booleans, arbitrary date strings and invalid Date objects.

Supported date formats

ts
1// Calendar date (interpreted at midnight UTC)2'2026-01-31'3 4// UTC date-time5'2026-01-31T10:30Z'6'2026-01-31T10:30:45Z'7'2026-01-31T10:30:45.123Z'8 9// Date-time with an explicit offset10'2026-01-31T10:30+03:00'11'2026-01-31T10:30:45-05:00'12 13// A valid Date instance14new Date('2026-01-31T10:30:00Z')

Calendar dates without a time are interpreted at midnight UTC. Date-time strings must include either Z or an explicit timezone offset. Fractional seconds are accepted up to nine digits, with precision beyond milliseconds truncated. Offsets are converted to the equivalent UTC instant in the returned Date.

Invalid date examples

ts
1// Invalid: no timezone offset on a date-time2'2026-01-31T10:30:00'3 4// Invalid: impossible calendar date5'2026-02-30'6 7// Invalid: unsupported date format8'Jan 31 2026'9 10// Invalid: numeric timestamp11176985540000012 13// Invalid: invalid Date object14new Date('invalid')
Date-time strings require an explicit timezone
Do not send ambiguous local date-times without a timezone. The validator rejects them so that the same input cannot represent different instants depending on the server's local timezone.

Nested object validation

Use Validator.object(shape) to validate nested plain objects. The nested shape uses the same field builders and presence rules as a root schema.

ts
1const AddressRule = defineSchema({2  city: Validator.string(2, 100).required(),3  country: Validator.text().required(),4  postalCode: Validator.text().optional(),5})6 7const CreateUserRule = defineSchema({8  name: Validator.text().required(),9  address: Validator.object({10    city: Validator.string(2, 100).required(),11    country: Validator.text().required(),12    postalCode: Validator.text().optional(),13  }).required(),14})

An existing schema can also be reused as the shape, for example Validator.object(AddressRule).required(). The nested shape is checked at compile time with the same field-name rules as a root schema.

Nested validation checks that the supplied value is a plain object. It recursively validates each declared property and reports errors using the full property path. A value that is not an object produces <field> must be an object.

ts
1{2  "address": {3    "city": "A",4    "country": ""5  }6}7 8// Example error keys:9{10  "address.city": ["address.city must be at least 2 characters"],11  "address.country": ["address.country is required"]12}

A plain object means an object whose prototype is Object.prototype or null. Arrays, null and class instances are not accepted as nested objects.

The object builder copies and freezes the supplied shape when it is created. Later changes to the original shape object do not change that builder's nested schema.

Text validation rules

The following rules are available on string() and text() validators. minLength() and maxLength() are only chainable on text(), because string(minLength, maxLength) already defines them.

  • minLength(limit) — requires at least the specified number of characters.
  • maxLength(limit) — limits the maximum number of characters.
  • email() — validates the value against the validator's email pattern.
  • url() — accepts valid HTTP or HTTPS URLs.
  • confirmed() — compares the field against its corresponding confirmation property.
  • trim() — removes whitespace from the beginning and end of the string.
  • lowercase() — converts the string to lowercase.

email()

Validates a string using the built-in email pattern. The pattern requires non-whitespace content before and after an @ character and a dot in the domain portion.

ts
1const EmailRule = defineSchema({2  email: Validator.text().email().required(),3})

The field name must contain email, regardless of letter casing, when using defineSchema().

ts
1// Valid field names2email: Validator.text().email().required()3contactEmail: Validator.text().email().required()4emailAddress: Validator.text().email().required()5 6// Invalid field name7contact: Validator.text().email().required()
Email validation is format checking
email() checks the value against a format pattern. It does not verify that the mailbox exists or that the user owns it.

url()

Validates a URL and only accepts the HTTP and HTTPS protocols. The value must contain an explicit protocol and a valid host. Leading or trailing whitespace and whitespace inside the URL are rejected.

ts
1const WebsiteRule = defineSchema({2  website: Validator.text().url().required(),3})
ts
1// Valid2'https://example.com'3'http://localhost:3000'4'https://example.com/profile'5 6// Invalid7'example.com'8'ftp://example.com'9'javascript:alert(1)'10'http:example.com'11'https://example.com/path with spaces'

confirmed()

Confirms a field against a sibling property whose name is the original field name followed by Confirmation. For example, password is compared with passwordConfirmation.

ts
1const RegisterRule = defineSchema({2  password: Validator.string(8, 100).confirmed().required(),3  passwordConfirmation: Validator.string(8, 100).required(),4})

The rule is only accepted on a property named exactly password. The comparison is strict, and both values must match after applying any transformations configured on the password field (the confirmation value is transformed the same way before it is compared).

For nested objects, the confirmation property is looked up beside the field inside that same object.

ts
1const AccountRule = defineSchema({2  credentials: Validator.object({3    password: Validator.string(8, 100).confirmed().required(),4    passwordConfirmation: Validator.string(8, 100).required(),5  }).required(),6})
Confirmation field naming matters
The validator does not search for arbitrary confirmation names. A field named password always checks passwordConfirmation.

Limits and ranges

Length, value and item-count limits are defined in one of two ways: as arguments of the factory, or by chaining the rule on a builder created without a range.

  • Validator.string(minLength, maxLength) — length range, always passed to the factory.
  • Validator.number(min, max) — value range passed to the factory, or Validator.number().min(limit).max(limit).
  • Validator.array(minItems, maxItems) — item-count range passed to the factory, or Validator.array().minItems(limit).maxItems(limit).
  • Validator.text().minLength(limit).maxLength(limit) — length limits chained on text().
ts
1const OrderRule = defineSchema({2  quantity: Validator.number().min(1).max(100).required(),3  discount: Validator.number(0, 100).optional(),4  items: Validator.array().minItems(1).maxItems(20).required(),5  notes: Validator.array(0, 5).optional(),6})

Numeric limits must be finite numbers. Length and item-count limits must be non-negative integers. A minimum cannot exceed its corresponding maximum.

Each rule can only be defined once on a builder, and a limit set by the factory counts as defined. Adding the same rule again is invalid. For example, Validator.number().min(1).min(2) and Validator.string(2, 50).minLength(5) are both rejected.

The limits are checked against the transformed value, so a trim() on a text field is applied before its length is measured.

Fluent API and rule availability

The available methods depend on the validator kind and on the arguments the factory already received. TypeScript exposes only the methods that are still valid for the current builder.

  • string: email, url, confirmed, trim, lowercase (minLength and maxLength are defined by the factory).
  • text: minLength, maxLength, email, url, confirmed, trim, lowercase.
  • number: min, max — only when created without arguments.
  • array: minItems, maxItems — only when created without arguments.
  • boolean / enum / date / object: presence rules only.

All field builders are immutable. Every method returns a new builder rather than modifying the existing one. This allows you to reuse an earlier builder safely.

ts
1const base = Validator.text()2 3const requiredName = base.required()4const optionalName = base.optional()5 6// base remains unchanged.7// requiredName and optionalName are independent builders.

A rule cannot be applied more than once. The email() and url() rules also exclude each other because they describe different formats.

defineSchema()

defineSchema() declares a schema and performs compile-time checks using the field names and builder states. It returns the original schema without transforming it.

ts
1const CreateAccountRule = defineSchema({2  email: Validator.text().email().required(),3  password: Validator.string(8, 100).confirmed().required(),4  passwordConfirmation: Validator.string(8, 100).required(),5})

It helps TypeScript detect schema mistakes before the application runs. The same checks are applied by Validator.validate() and Validator.object().

  • Every field must choose required(), nullable() or optional().
  • email() is only accepted when the property name contains email, case-insensitively.
  • confirmed() is only accepted on a property named password.
  • Every schema property must contain a validator builder.

InferSchema

Use InferSchema to obtain the TypeScript type represented by a schema. This prevents you from manually maintaining a separate interface that can become inconsistent with your validation rules.

ts
1import type { InferSchema } from 'lykosjs'2 3export const CreateUserRule = defineSchema({4  name: Validator.string(2, 50).required(),5  email: Validator.text().email().required(),6  age: Validator.number(18, 120).optional(),7})8 9export type CreateUserInput = InferSchema<typeof CreateUserRule>

The resulting type is inferred from the builder's value type and presence rule. Date fields infer to Date, enum arrays infer to a union of their string values, and nested objects infer their own property structure.

Validate data

Call Validator.validate(data, schema) to validate an untrusted object against a schema. The method returns a discriminated union that indicates whether validation succeeded.

ts
1const result = Validator.validate(body, CreateUserRule)2 3if (!result.valid) {4  return reply.UnprocessableContent({5    success: false,6    message: 'Validation failed',7    errors: result.errors,8  })9}10 11const user = result.data12 13return reply.Created({14  name: user.name,15  email: user.email,16})

Always check result.valid before accessing result.data. TypeScript narrows the result automatically: the successful branch contains data, while the failed branch contains errors.

A schema is compiled the first time it is used and the compiled plan is cached for that schema object. Reusing the same schema object across requests therefore avoids any repeated setup work.

Validation result types

The validation result is a discriminated union. Its valid property is the discriminant.

ts
1type ValidationErrors = Record<string, string[]>2 3type ValidationResult<T> =4  | {5      valid: true6      data: T7      errors: ValidationErrors8    }9  | {10      valid: false11      errors: ValidationErrors12    }

On success, data contains the validated and transformed object. On failure, errors contains the validation messages grouped by field path.

ts
1// Successful result2{3  valid: true,4  data: {5    name: 'Zen',6    email: 'zen@example.com'7  },8  errors: {}9}10 11// Failed result12{13  valid: false,14  errors: {15    name: ['name must be at least 2 characters'],16    email: ['email must be a valid email']17  }18}
data does not exist on failed results
Do not access result.data before checking result.valid. The failure branch intentionally does not contain a data property.

Validation errors

Errors are represented as a record where each key is the affected field path and each value is an array of messages. Nested fields use dot-separated paths.

ts
1{2  name: [3    'name must be at least 2 characters',4  ],5  email: [6    'email must be a valid email',7  ],8  'address.city': [9    'address.city must be at least 2 characters',10  ],11}

A field can have multiple error messages when multiple checks fail. Required-field failures stop further checks for that field. Type failures also stop checks that require the expected type.

Invalid schema definitions and invalid validation input are different from ordinary field validation failures. For example, a non-object input or an invalid schema can throw a TypeError instead of returning valid: false.

Default error messages

The messages below are generated by the validation rules, where <field> is the full field path.

  • required() — <field> is required
  • Type mismatch — <field> must be a string, a number, a boolean, an array, a valid date or an object
  • email() — <field> must be a valid email
  • url() — <field> must be a valid URL or <field> URL must use http or https
  • enum() — <field> must be one of: a, b, c
  • confirmed() — <field> confirmation does not match
  • min / max — <field> must be at least N / <field> may not be greater than N
  • minLength / maxLength — <field> must be at least N characters / <field> may not exceed N characters
  • minItems / maxItems — <field> must contain at least N items / <field> may not contain more than N items

Validate request bodies

Request bodies are untrusted input. Read the body as unknown, validate it, and only use the validated result after checking the success branch.

ts
1import { defineSchema, Validator } from 'lykosjs'2 3const CreateUserRule = defineSchema({4  name: Validator.string(2, 50).required(),5  email: Validator.text().email().trim().lowercase().required(),6  age: Validator.number(18, 120).optional(),7})8 9app.POST('/users', async (ctx, reply) => {10  const body = await ctx.json<unknown>()11 12  if (13    typeof body !== 'object' ||14    body === null ||15    Array.isArray(body)16  ) {17    return reply.BadRequest({ message: 'Request body must be an object' })18  }19 20  const result = Validator.validate(body, CreateUserRule)21 22  if (!result.valid) {23    return reply.UnprocessableContent({24      message: 'Validation failed',25      errors: result.errors,26    })27  }28 29  const user = result.data30 31  return reply.Created({32    name: user.name,33    email: user.email,34    age: user.age,35  })36})

The Validator.validate() method expects a Record<string, unknown>. If the body comes from ctx.json<unknown>(), first narrow it to an object before passing it to the validator.

Transforms

Text transformations normalize values before validation checks are executed. The supported transformations are trim() and lowercase().

ts
1const AccountRule = defineSchema({2  email: Validator.text().trim().lowercase().email().required(),3})

Transformations always execute in a fixed order, regardless of the order in which they were chained: trimming happens first, followed by lowercasing. Validation rules such as email() and url() inspect the transformed value.

ts
1// Input2{3  email: '  ZEN@EXAMPLE.COM  '4}5 6// Validated data7{8  email: 'zen@example.com'9}

The validator does not mutate the original input object. When a value changes (a text transformation, a date conversion or a change inside a nested object), it returns a shallow copy containing the new value. If nothing changes, the original object may be returned.

Nested transformations are also reflected in the returned nested object. Always use result.data rather than continuing to use the original request body.

Blank string behavior

An empty string or a string containing only whitespace is treated as a missing value for presence handling.

  • A required field rejects blank strings.
  • A nullable or optional field skips its normal checks for a blank string.
  • If a non-required text field has trim(), its whitespace-only value can be returned as an empty string after transformation.
ts
1const Rule = defineSchema({2  requiredName: Validator.text().required(),3  optionalName: Validator.text().trim().optional(),4})5 6// requiredName: '   ' -> validation error7// optionalName: '   ' -> transformed to ''

Nested validation errors

Nested object validation recursively checks its declared properties. Each nested error is reported using the complete path from the root object.

ts
1const UserRule = defineSchema({2  profile: Validator.object({3    firstName: Validator.text().required(),4    lastName: Validator.text().required(),5    address: Validator.object({6      city: Validator.text().required(),7    }).required(),8  }).required(),9})10 11// Example error key:12'profile.address.city'

This path format is useful when mapping validation errors to nested form fields or building a structured API response.

Configure error messages

The Validator exposes Validator.configure() for supplying an ErrorMessages instance. This configuration is static and shared by the Validator class.

ts
1Validator.configure(errorMessages)

The validator uses the configured error-message provider when compiling invalid schema definitions, such as a field that combines conflicting presence rules. Field validation messages are generated by the validation rules themselves. Because a schema is compiled once and cached, call Validator.configure() before validating with a schema if your application needs custom schema-definition error messages.

TypeScript mistakes

The fluent API uses TypeScript state to restrict invalid operations. The following examples show common mistakes and their correct alternatives.

Missing a presence rule

ts
1// Incorrect: presence is still unset2const Rule = defineSchema({3  name: Validator.text(),4})5 6// Correct7const Rule = defineSchema({8  name: Validator.text().required(),9})

Combining presence rules

ts
1// Incorrect: mutually exclusive rules2Validator.text().required().nullable()3 4// Incorrect: optional and required cannot coexist5Validator.text().optional().required()6 7// Correct: select one8Validator.text().required()9Validator.text().nullable()10Validator.text().optional()

Using a rule on the wrong type

ts
1// Incorrect: min() is not available on text2Validator.text().min(5)3 4// Incorrect: minLength() is not available on numbers5Validator.number().minLength(5)6 7// Incorrect: trim() is not available on arrays8Validator.array().trim()9 10// Correct11Validator.text().minLength(5)12Validator.number().min(5)13Validator.text().trim()

Applying the same rule twice

ts
1// Incorrect2Validator.text().minLength(2).minLength(5)3 4// Incorrect5Validator.number().min(1).min(2)6 7// Incorrect: the factory already defines the length range8Validator.string(2, 50).minLength(5)9 10// Incorrect: the factory already defines the value range11Validator.number(1, 100).min(5)12 13// Correct14Validator.text().minLength(2).maxLength(50)15Validator.number().min(1).max(100)16Validator.string(2, 50)17Validator.number(1, 100)

Combining email() and url()

ts
1// Incorrect: these rules conflict2Validator.text().email().url()3 4// Correct: choose the intended format5Validator.text().email().required()6Validator.text().url().required()

Using email() with the wrong property name

ts
1// Incorrect: property name does not contain "email"2const Rule = defineSchema({3  contact: Validator.text().email().required(),4})5 6// Correct7const Rule = defineSchema({8  contactEmail: Validator.text().email().required(),9})

Using confirmed() on another field

ts
1// Incorrect2const Rule = defineSchema({3  pin: Validator.text().confirmed().required(),4})5 6// Correct7const Rule = defineSchema({8  password: Validator.text().confirmed().required(),9  passwordConfirmation: Validator.text().required(),10})

Using incomplete number or array arguments

ts
1// Incorrect: only one argument2Validator.number(1)3Validator.array(1)4 5// Correct6Validator.number()7Validator.number(1, 100)8 9Validator.array()10Validator.array(1, 10)

Providing a single argument is rejected by TypeScript and also throws at runtime for plain JavaScript callers. Use either no arguments or both range arguments.

Invalid limits

ts
1// Incorrect: lower limit exceeds upper limit2Validator.string(50, 10)3 4// Incorrect: negative length5Validator.text().minLength(-1)6 7// Incorrect: fractional item count8Validator.array().minItems(1.5)9 10// Incorrect: non-finite number11Validator.number().min(Infinity)12 13// Correct14Validator.string(2, 50)15Validator.text().minLength(1)16Validator.array().minItems(1)17Validator.number().min(0)

Length and item-count limits must be non-negative integers. Numeric minimum and maximum limits must be finite numbers. A lower limit cannot exceed its corresponding upper limit.

Accessing validation data without narrowing

ts
1// Incorrect: data is not available on every result branch2const result = Validator.validate(body, CreateUserRule)3console.log(result.data.name)4 5// Correct6if (result.valid) {7  console.log(result.data.name)8} else {9  console.log(result.errors)10}

Passing unknown data without narrowing

ts
1// Incorrect: unknown is not a Record<string, unknown>2const body = await ctx.json<unknown>()3const result = Validator.validate(body, CreateUserRule)4 5// Correct6const body = await ctx.json<unknown>()7 8if (9  typeof body !== 'object' ||10  body === null ||11  Array.isArray(body)12) {13  return reply.BadRequest()14}15 16const result = Validator.validate(body, CreateUserRule)

Using the original body after validation

ts
1// Incorrect: this may contain unnormalized values2const result = Validator.validate(body, CreateUserRule)3 4if (!result.valid) {5  return reply.UnprocessableContent(result.errors)6}7 8return reply.OK({ email: body.email })9 10// Correct: use the validated output11return reply.OK({ email: result.data.email })

Validation exceptions versus validation failures

A normal field validation failure returns { valid: false, errors }. It does not automatically throw an exception or produce an HTTP response. Your route handler decides how to return those errors.

Some invalid inputs are programming or configuration errors and can throw instead. Examples include a non-object validation input, an invalid schema, a schema property that is not a validator, duplicate rules, invalid limits or conflicting builder rules.

ts
1const result = Validator.validate(body, CreateUserRule)2 3if (!result.valid) {4  return reply.UnprocessableContent({ errors: result.errors })5}6 7return reply.Created(result.data)

Complete example

The following example combines nested schemas, enum values, dates, transformations, optional fields and request validation in a single route.

ts
1import { defineSchema, InferSchema, Validator } from 'lykosjs'2 3const CreateCustomerRule = defineSchema({4  name: Validator.string(2, 100).required(),5 6  email: Validator.text().trim().lowercase().email().required(),7 8  role: Validator.enum([9    'customer',10    'business',11  ]).required(),12 13  age: Validator.number(18, 120).optional(),14 15  registeredAt: Validator.date().required(),16 17  address: Validator.object({18    city: Validator.text().required(),19    country: Validator.text().required(),20    postalCode: Validator.text().optional(),21  }).required(),22 23  website: Validator.text().url().nullable(),24})25 26type CreateCustomerInput = InferSchema<typeof CreateCustomerRule>27 28app.POST('/customers', async (ctx, reply) => {29  const body = await ctx.json<unknown>()30 31  if (32    typeof body !== 'object' ||33    body === null ||34    Array.isArray(body)35  ) {36    return reply.BadRequest({ message: 'Request body must be an object' })37  }38 39  const result = Validator.validate(body,CreateCustomerRule)40 41  if (!result.valid) {42    return reply.UnprocessableContent({43      success: false,44      message: 'Validation failed',45      errors: result.errors,46    })47  }48 49  const customer: CreateCustomerInput = result.data50 51  return reply.Created({52    success: true,53    data: customer,54  })55})

Best practices

  • Define schemas outside route handlers and reuse them instead of rebuilding them for every request. A schema object is compiled once and cached.
  • Use ctx.json<unknown>() for untrusted JSON input rather than pretending the request is already validated.
  • Narrow the request body to an object before calling Validator.validate().
  • Use defineSchema() to catch invalid field names and unfinished builder configurations at compile time.
  • Use InferSchema to keep application types synchronized with their schemas.
  • Always narrow the result using result.valid before accessing result.data.
  • Use result.data after validation so that normalized values are preserved.
  • Prefer passing ranges to string(), number() and array() when both limits are known.
  • Remember that array validation checks the array and its length, not the types of its individual elements.
  • Use explicit timezone information for date-time strings.
  • Treat thrown schema and input errors separately from ordinary validation failures.
Validation is not a replacement for authorization
Validation ensures that incoming data matches the expected schema. It does not determine whether the current user is allowed to perform an operation or access a resource. Keep authentication, authorization and business-rule checks in their appropriate layers.