validationschemalibrary
v1.0.0
Published
A lightweight, type-safe validation and schema library for JavaScript and TypeScript
Downloads
83
Maintainers
Readme
validify
A lightweight, type-safe validation and schema library for JavaScript and TypeScript. Built for form validation, API input validation, and runtime type checking with full TypeScript inference.
📖 Full documentation (فارسی): docs/DOCUMENTATION.md — API reference
Installation
npm install validifyFeatures
- Type-safe – Full TypeScript support with automatic type inference
- Lightweight – Zero dependencies, tree-shakeable API
- i18n-ready – Error codes suitable for localization
- Composable – Build complex schemas from simple ones
- Flexible – Use
parse()to throw, orsafeParse()for controlled handling
Quick Start
import { string, number, object, optional } from 'validify';
const userSchema = object({
name: string({ minLength: 1, maxLength: 100 }),
email: string({ email: true }),
age: optional(number({ min: 0, max: 150 })),
});
// Parse (throws on failure)
const user = userSchema.parse({ name: 'Alice', email: '[email protected]' });
// user: { name: string; email: string; age: number | undefined }
// Safe parse (returns result object)
const result = userSchema.safeParse(input);
if (result.success) {
console.log(result.data);
} else {
console.error(result.issues);
}Schema Types
string
string({ minLength?: number, maxLength?: number, pattern?: RegExp, email?: boolean, url?: boolean, trim?: boolean })number
number({ min?: number, max?: number, integer?: boolean })boolean
boolean()array
array({ minLength?: number, maxLength?: number, itemSchema?: Schema<T> })object
object({ key: schema, ... })optional
Wraps any schema to allow undefined or null:
object({
name: string(),
nickname: optional(string()),
})enum
enumSchema(['a', 'b', 'c'] as const)Error Handling
import { ValidationError } from 'validify';
try {
schema.parse(data);
} catch (err) {
if (err instanceof ValidationError) {
// All validation issues
console.log(err.issues);
// For form fields: { fieldPath: message }
const fieldErrors = err.toFieldMap();
// For i18n: [{ code, path, value }]
const report = err.toReport();
}
}Composing Schemas
import { compose, string } from 'validify';
const trimmedEmail = compose(
string({ trim: true }),
string({ email: true })
);Merging Object Shapes
import { merge, object, string, number } from 'validify';
const baseShape = { id: number() };
const userShape = { name: string(), email: string({ email: true }) };
const schema = merge(baseShape, userShape);i18n
Error codes are exposed for mapping to localized messages:
import { ErrorCodes } from 'validify';
// ErrorCodes: invalid_type, string_too_short, string_email, number_too_small, ...License
MIT © Alireza Aminzadeh
