ts-fast-validate
Version:
A lightweight, fast, and tree-shakable validation library focused on performance and developer experience. Alternative to Zod/Yup for JSON, API responses, and form validation.
250 lines (195 loc) • 5.77 kB
Markdown
# ts-fast-validate
A lightweight, fast, and tree-shakable validation library focused on performance and developer experience. Alternative to Zod/Yup for JSON, API responses, and form validation.
## 🚀 Features
- **Lightning Fast**: Optimized for performance with minimal overhead
- **Tree-shakable**: Import only what you need
- **TypeScript First**: Full type safety and inference
- **Small Bundle Size**: Minimal impact on your bundle
- **Familiar API**: Easy migration from Zod/Yup
- **Zero Dependencies**: No external dependencies
## 📦 Installation
```bash
npm install ts-fast-validate
# or
yarn add ts-fast-validate
# or
pnpm add ts-fast-validate
```
## 🔧 Basic Usage
```typescript
import { string, number, boolean, object, array, email } from 'ts-fast-validate';
// Define a schema
const userSchema = object({
name: string(),
email: email(),
age: number(),
isActive: boolean(),
tags: array(string()).optional()
});
// Validate data (throws on error)
const user = userSchema.parse({
name: 'John Doe',
email: 'john@example.com',
age: 25,
isActive: true
});
// Safe validation (returns result object)
const result = userSchema.safeParse(userData);
if (result.success) {
console.log(result.data); // Typed data
} else {
console.log(result.error); // Validation error with path
}
```
## 📚 API Reference
### Basic Types
```typescript
import { string, number, boolean, literal } from 'ts-fast-validate';
const nameSchema = string();
const ageSchema = number();
const isActiveSchema = boolean();
const roleSchema = literal('admin'); // Only accepts 'admin'
```
### String Validators
```typescript
import { string, email, url, uuid, stringMin, stringMax, length, regex } from 'ts-fast-validate';
const emailSchema = email();
const urlSchema = url();
const uuidSchema = uuid();
const minLengthSchema = stringMin(3)(string());
const maxLengthSchema = stringMax(50)(string());
const exactLengthSchema = length(10)(string());
const regexSchema = regex(/^[A-Z]+$/)(string());
```
### Number Validators
```typescript
import { number, int, positive, negative, nonnegative, numberMin, numberMax, finite } from 'ts-fast-validate';
const integerSchema = int();
const positiveSchema = positive();
const negativeSchema = negative();
const nonNegativeSchema = nonnegative();
const minSchema = numberMin(0)(number());
const maxSchema = numberMax(100)(number());
const finiteSchema = finite();
```
### Complex Types
```typescript
import { object, array, union, record } from 'ts-fast-validate';
// Objects
const userSchema = object({
id: number(),
name: string(),
email: email()
});
// Arrays
const numbersSchema = array(number());
const usersSchema = array(userSchema);
// Unions
const statusSchema = union(
literal('pending'),
literal('approved'),
literal('rejected')
);
// Records (key-value maps)
const metadataSchema = record(string());
```
### Schema Modifiers
```typescript
// Optional fields
const optionalSchema = string().optional(); // string | undefined
// Nullable fields
const nullableSchema = string().nullable(); // string | null
// Default values
const defaultSchema = string().default('hello');
// Custom validation
const customSchema = string().refine(
(value): value is string => value.length > 5,
'Must be longer than 5 characters'
);
// Transform values
const upperSchema = string().transform(s => s.toUpperCase());
// Chaining
const complexSchema = string()
.optional()
.default('default')
.transform(s => s.toUpperCase());
```
## 🎯 Real-world Examples
### API Response Validation
```typescript
import { object, array, number, string, boolean } from 'ts-fast-validate';
const apiResponseSchema = object({
success: boolean(),
data: array(object({
id: number(),
title: string(),
published: boolean(),
author: object({
name: string(),
email: email()
})
})),
pagination: object({
page: number(),
limit: number(),
total: number()
})
});
// Use with fetch
const response = await fetch('/api/posts');
const json = await response.json();
const validatedData = apiResponseSchema.parse(json);
```
### Form Validation
```typescript
import { object, string, email, stringMin } from 'ts-fast-validate';
const signupFormSchema = object({
username: stringMin(3)(string()),
email: email(),
password: stringMin(8)(string()),
confirmPassword: string()
}).refine(
(data): data is typeof data => data.password === data.confirmPassword,
'Passwords must match'
);
function handleFormSubmit(formData: FormData) {
const result = signupFormSchema.safeParse({
username: formData.get('username'),
email: formData.get('email'),
password: formData.get('password'),
confirmPassword: formData.get('confirmPassword')
});
if (!result.success) {
console.error('Validation errors:', result.error);
return;
}
// Form data is now validated and typed
console.log('Valid form data:', result.data);
}
```
## ⚡ Performance
ts-fast-validate is designed for speed:
- **Fast validation**: Optimized validation logic with minimal overhead
- **Tree-shakable**: Bundle only the validators you use
- **Zero dependencies**: No external dependency overhead
- **Small footprint**: Minimal impact on bundle size
## 🔄 Migration from Zod
ts-fast-validate has a similar API to Zod, making migration straightforward:
```typescript
// Zod
import { z } from 'zod';
const schema = z.object({
name: z.string(),
age: z.number().positive()
});
// ts-fast-validate
import { object, string, positive } from 'ts-fast-validate';
const schema = object({
name: string(),
age: positive()
});
```
## 📄 License
MIT
## 🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.