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:
npm i @nhtio/validationpnpm add @nhtio/validationyarn add @nhtio/validationExample Usage
Define your schema
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
const { value, error } = schema.validate(myVeryImportantValue)Export your schema for consumption in another application
import { encode } from '@nhtio/validation'
const exported = encode(schema); // stringImport the schema from another application
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:
bigint- A schema for number-like validation ofBigIntvaluesdatetime- A schema for handling of Luxon DateTime objects with keyword supportphone- A schema for validating phone numbers using Google's libphonenumber
DateTime Schema with Keywords
The datetime schema supports intuitive keyword values for human-readable date constraints:
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.