Universal data validation utilities using JSON Schema, Zod, and custom validation rules
npm install @bernierllc/schema-validatorUniversal data validation utilities using JSON Schema, Zod, and custom validation rules.
``bash`
npm install @bernierllc/schema-validator
`typescript
import { createValidator } from '@bernierllc/schema-validator';
const schema = {
type: 'json-schema',
schema: {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
age: { type: 'number', minimum: 0 },
email: { type: 'string', format: 'email' }
},
required: ['name', 'age']
}
};
const validator = createValidator(schema);
// Async validation
const result = await validator.validate({
name: 'John',
age: 30,
email: 'john@example.com'
});
if (result.valid) {
console.log('Data is valid:', result.data);
} else {
console.log('Validation errors:', result.errors);
}
// Sync validation
const syncResult = validator.validateSync(data);
`
`typescript
import { z } from 'zod';
import { createValidator } from '@bernierllc/schema-validator';
const zodSchema = z.object({
name: z.string().min(1),
age: z.number().min(0),
email: z.string().email().optional()
});
const schema = {
type: 'zod',
schema: zodSchema
};
const validator = createValidator(schema);
const result = await validator.validate(data);
`
`typescript
import { createValidator, createValidationError } from '@bernierllc/schema-validator';
const customValidator = {
validate: async (data) => {
if (typeof data !== 'string' || data.length < 3) {
return {
valid: false,
errors: [createValidationError('', 'String must be at least 3 characters', 'min-length')],
warnings: [],
metadata: { backend: 'custom', duration: 0, transformations: [] }
};
}
return {
valid: true,
data: data,
errors: [],
warnings: [],
metadata: { backend: 'custom', duration: 0, transformations: [] }
};
}
};
const schema = {
type: 'custom',
schema: customValidator
};
const validator = createValidator(schema);
const result = await validator.validate('hello');
`
`typescript
import { createValidator } from '@bernierllc/schema-validator';
const schema = {
type: 'json-schema',
schema: {
type: 'object',
properties: {
name: { type: 'string' },
status: { type: 'string', default: 'active' }
}
},
options: {
useDefaults: true, // Apply default values
coerce: true, // Type coercion
strict: true, // Strict validation
abortEarly: false, // Continue on errors
removeAdditional: false, // Keep extra properties
allowUnknown: false // Disallow unknown properties
}
};
const validator = createValidator(schema);
`
- createValidator - Create a validator instancevalidate
- - One-shot async validationvalidateSync
- - One-shot sync validationcompileSchema(schema: ValidationSchema): CompiledSchema
- - Pre-compile schema for reusemergeSchemas(schemas: ValidationSchema[]): ValidationSchema
- - Merge multiple schemas
`typescript
interface ValidationResult
valid: boolean;
data?: T;
errors: ValidationError[];
warnings: ValidationWarning[];
metadata: {
backend: string;
duration: number;
transformations: string[];
};
}
interface ValidationError {
path: string;
message: string;
code: string;
value?: any;
expected?: any;
}
`
- Multiple Backends: JSON Schema (ajv), Zod, and custom validators
- Type Safety: Full TypeScript support with type inference
- Performance: Schema compilation and caching
- Detailed Errors: Structured error reporting with paths
- Transformations: Data coercion, defaults, and cleanup
- Async Support: Both synchronous and asynchronous validation
- Extensible: Custom validation functions and rules
1. JSON Schema - Industry standard schema validation
2. Zod - TypeScript-first schema validation
3. Custom - Your own validation functions
All validation results include detailed error information:
`typescript
const result = await validator.validate(invalidData);
if (!result.valid) {
result.errors.forEach(error => {
console.log(${error.path}: ${error.message} (${error.code}));`
});
}
- Schemas are compiled once for optimal performance
- Validation duration is tracked in metadata
- Support for schema caching and reuse
This package supports optional integration with @bernierllc/logger for enhanced logging capabilities:
`typescript`
import { createValidator } from '@bernierllc/schema-validator';
// Logger integration is automatically detected when available
// No additional setup required - the package provides graceful degradation
When @bernierllc/logger is available in your project:
- Validation errors are logged with structured data
- Performance metrics are tracked
- Debug information is available for troubleshooting
This package supports optional integration with @bernierllc/neverhub-adapter for service discovery and event communication:
`typescript``
// NeverHub integration is automatically detected and configured
// The package provides graceful degradation when NeverHub is not available
When NeverHub is available:
- Validation events can be published to the event bus
- Service discovery allows dynamic configuration
- Health monitoring and metrics reporting is enabled
All integrations are optional and the package works fully without them:
- No Logger: Uses console logging as fallback
- No NeverHub: Functions as standalone package
- No External Dependencies: Core functionality always available
Copyright (c) 2025 Bernier LLC. All rights reserved.
This package is licensed under the Bernier LLC license. See LICENSE file for details.