Skip to content

Quickstart

Validation is designed to be easily installed and implemented within both browser and server side projects

It is built on top of Joi, but provides additional schemas and functionality built-in.

Installation

Install @nhtio/validation directly from your preferred package manager using one of the following commands:

sh
npm i @nhtio/validation
sh
pnpm add @nhtio/validation
sh
yarn add @nhtio/validation

Example Usage

Define your schema

typescript
import { validator } from '@nhtio/validation'

const schema = validator.object({
    username: validator.string().alphanum().min(3).max(30).required(),
    password: validator.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
    repeat_password: validator.ref('password'),
    access_token: validator.alternatives(
        validator.string(),
        validator.number()
    ),
    birth_year: validator.number().integer().min(1900).max(2013),
    email: validator.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
}).with('username', 'birth_year').xor('password', 'access_token').with('password', 'repeat_password')

Validate your values

typescript
const { value, error } = schema.validate(myVeryImportantValue)

Export your schema for consumption in another application

typescript
import { encode } from '@nhtio/validation'

const exported = encode(schema); // string

Import the schema from another application

typescript
import { decode } from '@nhtio/validation'

const schema = decode(exported)
const { value, error } = schema.validate(myOtherVeryImportantValue)

Additional Schemas

In addition to the standard schemas which are provided by Joi by default, @nhtio/validation also includes:

DateTime Schema with Keywords

The datetime schema supports intuitive keyword values for human-readable date constraints:

typescript
import { validator } from '@nhtio/validation'

// Using keywords for validation
const schema = validator.datetime()
    .after('yesterday')
    .before('end of month')
    .weekday()

// Validate with keywords
schema.validate('today')  // Valid if today is a weekday before end of month

// Available keywords include:
// - Time: 'now'
// - Days: 'today', 'yesterday', 'tomorrow'
// - Weeks: 'start of week', 'end of week', 'last week', 'next week'
// - Months: 'start of month', 'end of month', 'last month', 'next month'
// - Years: 'start of year', 'end of year', 'last year', 'next year'
// - CamelCase variants: 'startOfWeek', 'endOfMonth', etc.

Keywords are operator-aware: beforeOrEqual('today') includes the entire day (00:00 - 23:59:59.999), making "on or before today" work as expected.

See Also