Skip to content

Lightweight & performant form & request data validation library.

License

Notifications You must be signed in to change notification settings

stacksjs/ts-validation

Repository files navigation

Social Card of this repo

npm version GitHub Actions Commitizen friendly

@stacksjs/ts-validation

A lightweight, type-safe validation library for TypeScript with blazing-fast performance, built for Bun.

Features

  • πŸš€ 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

Installation

# 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

Quick Start

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)
}

Validation Types

String Validation

// 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()

Number Validation

// 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

// Boolean validation
const termsAcceptedValidator = v.boolean().required()

Array Validation

// 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

// 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

// 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)

Configuration

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

Performance Tips

  1. Use caching: Enable cacheResults in the config for repeated validations
  2. Early returns: Set strictMode: true to stop on first error when validating complex objects
  3. Reuse validators: Create validators once and reuse them instead of creating new ones for each validation

Testing

bun test

Changelog

Please see our releases page for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Community

For help, discussion about best practices, or any other conversation that would benefit from being searchable:

Discussions on GitHub

For casual chit-chat with others using this package:

Join the Stacks Discord Server

Credits

  • validator.js - for the original string validation functions

Postcardware

"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 🌎

Sponsors

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.

License

The MIT License (MIT). Please see LICENSE for more information.

Made with πŸ’™