abit-validator
v1.0.1
Published
abit-validator schema from scratch
Maintainers
Readme
ABIT Validator
A lightweight, type-safe validation library for JavaScript/TypeScript with a fluent API.
Installation
npm install abit-validatorFeatures
Type-safe validation with TypeScript support
Fluent API for building validation schemas
Support for primitive types, objects, and arrays
Custom error messages
Optional, nullable, and default values
Transformation of validated data
Composition with or operator
Basic Usage
import abitValidator from 'abit-validator';
// Create a validator
const userValidator = abitValidator.object({
name: abitValidator.string().min(3).max(50),
age: abitValidator.number().min(18),
email: abitValidator.string().email(),
isAdmin: abitValidator.boolean().optional(),
tags: abitValidator.array(abitValidator.string()).min(1).max(5),
});
// Validate data
try {
const user = userValidator.parse({
name: 'John Doe',
age: 25,
email: '[email protected]',
tags: ['developer', 'typescript'],
});
console.log('Valid user:', user);
} catch (error) {
console.error('Validation failed:', error);
}
// Safe parse (without throwing)
const result = userValidator.safeParse(someData);
if (result.success) {
console.log('Valid data:', result.data);
} else {
console.error('Validation errors:', result.errors);
}Validator Types
Primitive Validators
String Validation
| Method | Description |
| ------------------------ | -------------------------------- |
| abitValidator.string() | Base string validator |
| .min(length) | Minimum string length |
| .max(length) | Maximum string length |
| .length(len) | Exact string length |
| .email() | Must be a valid email format |
| .startsWith(value) | Must start with a specific value |
| .regex(pattern) | Must match a regular expression |
Number Validation
| Method | Description |
| ------------------------ | --------------------- |
| abitValidator.number() | Base number validator |
| .min(value) | Minimum numeric value |
| .max(value) | Maximum numeric value |
Boolean Validation
| Method | Description |
| ------------------------- | ---------------------- |
| abitValidator.boolean() | Base boolean validator |
Complex Validators
| Method | Description |
| ------------------------------ | -------------------------------------------------- |
| abitValidator.object(schema) | Validates an object based on a shape/schema object |
| | (i.e. { key: validator }) |
Array Validation
| Method | Description |
| -------------------------------- | ---------------------------------------------------------- |
| abitValidator.array(validator) | Validates an array where all items use the given validator |
| .min(length) | Minimum array length |
| .max(length) | Maximum array length |
| .nonempty() | Array must not be empty |
Utility Methods
| Method | Description |
| ----------------------------- | ------------------------------------------------------- |
| .optional() | Makes the field optional (i.e., undefined is allowed) |
| .nullable() | Allows null as a valid value |
| .default(value) | Provides a default value if the input is undefined |
| .refine(validator, message) | Adds a custom validation with an error message |
| .or(otherValidator) | Allows alternative validation if the first fails |
| .transform(fn) | Transforms the validated value using a function |
| .instanceof(constructor) | Checks if the value is an instance of a given class |
| .enum(enumObj) | Validates that the value is one of the enum's values |
| .literal(value) | Ensures the value exactly matches the given value |
Error Handling
The library throws ValidationError with detailed error information when validation fails. You can also use safeParse to get validation results without throwing.
Custom Validation
const passwordValidator = abitValidator
.string()
.min(8)
.refine(
(val) => /[A-Z]/.test(val) && /[0-9]/.test(val),
'Password must contain at least one uppercase letter and one number',
);Type Safety
All validators are fully typed and preserve TypeScript type information through transformations and compositions.
License MIT
