A lightweight, type-safe validation library for TypeScript with blazing-fast performance, built for Bun.
- π Blazing fast performance - Optimized for speed
- π Type-safe - Full TypeScript support with strong typing
- π Fluent API - Chain validation rules for clean, readable code
- ποΈ Composable - Create reusable validations and schemas
- π§© Extendable - Easy to add custom validators
- πΎ Tiny footprint - Lightweight with no dependencies
- π Detailed errors - Comprehensive error reporting
# Using bun
bun add @stacksjs/ts-validation
# Using npm
npm install @stacksjs/ts-validation
# Using yarn
yarn add @stacksjs/ts-validation
# Using pnpm
pnpm add @stacksjs/ts-validation
import { v } from '@stacksjs/ts-validation'
// Create a validator for a user object
const userValidator = v.object().shape({
name: v.string().min(2).max(50).required(),
email: v.string().email().required(),
age: v.number().min(18).integer().required(),
website: v.string().url().optional(),
tags: v.array().each(v.string()).optional(),
})
// Validate a user object
const user = {
name: 'John Doe',
email: 'john@example.com',
age: 25,
website: 'https://example.com',
tags: ['developer', 'TypeScript'],
}
const result = userValidator.validate(user)
if (result.valid) {
console.log('User is valid!')
}
else {
console.error('Validation errors:', result.errors)
}
// Basic string validation
const nameValidator = v.string().min(2).max(50).required()
// Email validation
const emailValidator = v.string().email().required()
// URL validation
const websiteValidator = v.string().url().optional()
// Pattern matching
const zipCodeValidator = v.string().matches(/^\d{5}$/).required()
// Alphanumeric, alpha, or numeric characters
const usernameValidator = v.string().alphanumeric().required()
// Basic number validation
const ageValidator = v.number().min(18).max(120).required()
// Integer validation
const quantityValidator = v.number().integer().positive().required()
// Negative numbers
const temperatureValidator = v.number().negative().required()
// Boolean validation
const termsAcceptedValidator = v.boolean().required()
// Array validation
const tagsValidator = v.array().min(1).max(10).required()
// Validate each item in the array
const numbersValidator = v.array().each(v.number().positive()).required()
// Array with specific length
const coordinatesValidator = v.array().length(2).each(v.number()).required()
// Object validation
const addressValidator = v.object().shape({
street: v.string().required(),
city: v.string().required(),
state: v.string().length(2).required(),
zip: v.string().matches(/^\d{5}$/).required(),
})
// Nested object validation
const userValidator = v.object().shape({
name: v.string().required(),
address: addressValidator,
})
// Strict object validation (no extra fields allowed)
const strictValidator = v.object().strict().shape({
id: v.number().required(),
name: v.string().required(),
})
// Custom validation
const isEven = (val: number) => val % 2 === 0
const evenNumberValidator = v.custom(isEven, 'Number must be even')
// Complex custom validation
const passwordValidator = v.string()
.min(8)
.matches(/[A-Z]/)
.matches(/[a-z]/)
.matches(/\d/)
.matches(/[^A-Z0-9]/i)
You can customize the validation behavior by modifying the validation.config.ts
file:
// validation.config.ts
import type { ValidationOptions } from '@stacksjs/ts-validation'
const config: ValidationOptions = {
verbose: true, // Enable detailed error messages
strictMode: false, // Stop on first error if true
cacheResults: true, // Cache validation results for better performance
errorMessages: {
// Customize error messages
required: '{field} is required',
email: '{field} must be a valid email address',
// ...more custom messages
},
}
export default config
- Use caching: Enable
cacheResults
in the config for repeated validations - Early returns: Set
strictMode: true
to stop on first error when validating complex objects - Reuse validators: Create validators once and reuse them instead of creating new ones for each validation
bun test
Please see our releases page for more information on what has changed recently.
Please see CONTRIBUTING for details.
For help, discussion about best practices, or any other conversation that would benefit from being searchable:
For casual chit-chat with others using this package:
Join the Stacks Discord Server
- validator.js - for the original string validation functions
"Software that is free, but hopes for a postcard." We love receiving postcards from around the world showing where Stacks is being used! We showcase them on our website too.
Our address: Stacks.js, 12665 Village Ln #2306, Playa Vista, CA 90094, United States π
We would like to extend our thanks to the following sponsors for funding Stacks development. If you are interested in becoming a sponsor, please reach out to us.
The MIT License (MIT). Please see LICENSE for more information.
Made with π