sanitizer-ts
v0.0.1
Published
Schema-based data sanitizer for data transformation.
Downloads
114
Maintainers
Readme
DataSanitizer
DataSanitizer is a small schema-based sanitization library for JavaScript and TypeScript. It applies transformation and validation rules by runtime value type, making it useful when you need a lightweight normalization step before storing, validating, or forwarding incoming data.
The package exposes:
- reusable transformers for strings, numbers, booleans, and objects;
- reusable validators for the same value groups;
- a sanitizer factory for preconfigured pipelines;
- direct
sanitizeandvalidatehelper functions.
How It Works
DataSanitizer uses a schema keyed by JavaScript runtime types:
type SchemaDefinition = {
string?: { transformers?: Transformer[]; validators?: Validator[] };
number?: { transformers?: Transformer[]; validators?: Validator[] };
boolean?: { transformers?: Transformer[]; validators?: Validator[] };
object?: { transformers?: Transformer[]; validators?: Validator[] };
};When sanitizing or validating:
- primitive values use the schema entry matching their runtime type;
- object inputs are processed field-by-field;
- each object field is matched by the field value type, not by the field name;
- if a type has no configured rules, the value is returned unchanged and validation passes.
Installation
npm install sanitizer-tsAPI
createSanitizer(schema)
Creates a reusable sanitizer object with:
sanitize(data)validate(data)schema(frozen copy of the provided schema)
Use this when the same schema is applied repeatedly.
sanitize(data, schemaOrSanitizer)
Sanitizes a primitive value or an object.
- If the second argument is a schema, a sanitizer is created internally.
- If the second argument already has
sanitizeandvalidatemethods, it is used directly.
validate(data, schemaOrSanitizer)
Validates a primitive value or an object and returns:
{
valid: boolean;
errors: Record<string, string[]>;
}Built-In Transformers
Strings
trimtoLowerCasetoUpperCasecollapseWhitespacetruncate(max)defaultIfEmpty(defaultValue)
Numbers
clamp(min, max)round(decimals = 0)abs
Booleans
toBoolean
NOTE: toBoolean can coerce strings, numbers, and booleans, but it only runs when assigned to the schema entry that receives that runtime value.
Objects
omit(keys)stripNullsnormalizeKeys(style)wherestyleiscamel,snake, orkebab
Built-In Validators
Strings
isStringisNotEmptyminLength(min)maxLength(max)matchesPattern(regex)isEmail
Numbers
isNumbermin(minValue)max(maxValue)positive
Booleans
isBooleanisTruthyisFalsey
Objects
hasKeys(requiredKeys)noNullsnoExtraKeys(allowedKeys)
Practical Examples
Normalize user-facing strings
import { collapseWhitespace, sanitize, toLowerCase, trim } from 'sanitizer-ts';
const value = ' HELLO WORLD ';
console.log(
sanitize(value, {
string: { transformers: [trim, collapseWhitespace, toLowerCase] },
}),
);
// 'hello world'Validate numeric ranges
import { validate, min, max } from 'sanitizer-ts';
const result = validate(150, {
number: { validators: [min(0), max(100)] },
});
console.log(result);
// { valid: false, errors: { value: ['max is 100'] } }Sanitize object values by type
import {
collapseWhitespace,
createSanitizer,
normalizeKeys,
round,
stripNulls,
trim
} from 'sanitizer-ts';
const sanitizer = createSanitizer({
string: { transformers: [trim, collapseWhitespace] },
number: { transformers: [round(2)] },
object: { transformers: [normalizeKeys('camel'), stripNulls] },
});
const input = {
name: ' Alice ',
score: 42.9876,
profile: { 'phone-number': null, role_name: 'admin' },
};
console.log(sanitizer.sanitize(input));
// {
// name: 'Alice',
// score: 42.99,
// profile: { roleName: 'admin' }
// }Coerce string flags with toBoolean
import { sanitize, toBoolean } from 'sanitizer-ts';
console.log(
sanitize('yes', {
string: { transformers: [toBoolean] },
}),
);
// trueBehavior Notes And Limitations
- Schemas are type-driven, not field-driven. You cannot assign separate rules to
emailandnameif both are strings without creating custom higher-level logic around the library. - Type matching happens before transformation. For example, a string value inside an object will use the
stringrules even if your end goal is to convert it into a boolean or number. - Arrays are not treated as valid input types by the current implementation.
nullandundefinedare rejected for both sanitization and validation.- Nested objects are handled as object values. Their inner properties are not recursively sanitized unless you apply another sanitizer yourself.
