valsan
v2.5.0
Published
Validation and sanitization library for TypeScript
Maintainers
Readme
ValSan
ValSan provides a clean, type-safe way to validate and transform data and input.
Features
- Type-safe - Full TypeScript support with generics
- Async-first - Built for I/O operations (supports DB checks, API calls)
- Structured errors - Machine-readable error codes with context
- Type transformation - Convert types during sanitization
- Configurable - Pass options to customize validator behavior
- Extensible - Create your own ValSans
- Composable - Build validation/sanitization pipelines
Install
npm install valsanQuick Start
What is a ValSan?
A ValSan is a Validator + Sanitizer. It checks input data, and returns it in a clean and consistent type/format.
Example - Object Validation & Sanitization
import {
ObjectValSan,
LengthValidator,
LowercaseSanitizer,
TrimSanitizer,
EmailValidator,
ComposedValSan
} from 'valsan';
const usernameValSan = new ComposedValSan<string, string>([
new TrimSanitizer(),
new LengthValidator({ minLength: 5, maxLength: 10 }),
new LowercaseSanitizer(),
]);
// Create an object validator
const validator = new ObjectValSan({
schema: {
username: usernameValSan,
optionalUsername: usernameValSan.copy({ isOptional: true }),
email: new EmailValidator(),
}
});
// Validate & sanitize input data
const result = await validator.run({
username: 'alice',
email: '[email protected]'
});
if (result.success) {
console.log('Sanitized:', result.data);
}
else {
console.error('Validation errors:', result.errors);
}
// ObjectValSan can also be nested for complex structures:
const addressSchema = new ObjectValSan({
schema: {
street: new TrimSanitizer(),
city: new TrimSanitizer(),
}
});
const userValidator = new ObjectValSan({
schema: {
username: usernameValSan,
email: new EmailValidator(),
address: addressSchema, // Nested object
}
});Note:
ObjectSanitizeris now deprecated in favor ofObjectValSan.ObjectSanitizerwill be removed in a future major version.
Using Built-in Primitives
ValSan includes ready-to-use primitive validators for common validation tasks:
import { RangeValidator } from 'valsan';
// Number validation
const range = new RangeValidator({ min: 0, max: 100 });
const result = await range.run(150);
console.log(result.success); // false - out of rangePrimitives Library
Compose your own validators from built-in primitives:
More
Contributing & Development
See contributing.md for information on how to develop or contribute to this project!
