biz-dynamic-object-validator
v1.0.0
Published
A Node.js package for dynamically validating objects using TypeScript.
Downloads
9
Maintainers
Readme
Biz Dynamic Object Validator
A dynamic object validator for TypeScript that allows you to define flexible and reusable validation schemas. Enhance your Node.js applications with robust and type-safe object validation.
Table of Contents
- Introduction
- Features
- Installation
- Getting Started
- API Documentation
- Validator
- SchemaBuilder
- FieldBuilder
- required(): FieldBuilder
- type(type: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'date'): FieldBuilder
- mustBeTrue(): FieldBuilder
- mustBeFalse(): FieldBuilder
- minLength(length: number): FieldBuilder
- maxLength(length: number): FieldBuilder
- pattern(regex: RegExp): FieldBuilder
- enum(values: string[]): FieldBuilder
- min(value: number): FieldBuilder
- max(value: number): FieldBuilder
- integer(): FieldBuilder
- minItems(count: number): FieldBuilder
- maxItems(count: number): FieldBuilder
- uniqueItems(): FieldBuilder
- items(schema: ValidationRule): FieldBuilder
- schema(nestedSchema: ValidationSchema): FieldBuilder
- before(date: Date): FieldBuilder
- after(date: Date): FieldBuilder
- custom(validator: ValidatorFunction): FieldBuilder
- done(): SchemaBuilder
- Examples
- License
- Acknowledgments
Introduction
In modern web development, validating user input and ensuring data integrity is crucial. Biz Dynamic Object Validator offers a flexible and type-safe way to define and enforce validation rules for your objects dynamically. Whether you're building APIs, forms, or any data-driven application, this package provides the tools you need to maintain robust data validation.
Features
- Dynamic Validation: Define validation rules at runtime without being constrained by static interfaces.
- Type Safety: Built with TypeScript to leverage strong typing and enhance development experience.
- Custom Rules: Create custom validation functions tailored to your specific needs.
- Comprehensive Type Support: Validate various data types including strings, numbers, booleans, arrays, objects, and dates.
- Fluent API: Intuitive and chainable API for building complex validation schemas effortlessly.
- Nested Validation: Validate nested objects and arrays with ease.
- Detailed Error Reporting: Receive comprehensive error messages to identify and rectify validation issues quickly.
Installation
Install biz-dynamic-object-validator using npm or yarn:
npm install biz-dynamic-object-validator
or
yarn add biz-dynamic-object-validator
Getting Started
Importing the Validator
First, import the necessary classes from the package:
import { Validator } from 'biz-dynamic-object-validator';
import { SchemaBuilder } from 'biz-dynamic-object-validator';
Defining a Validation Schema
Use the SchemaBuilder
to define your validation rules in a fluent and readable manner.
const schemaBuilder = new SchemaBuilder();
const userSchema = schemaBuilder
.field('isActive')
.required()
.type('boolean')
.mustBeTrue() // The field must be true
.done()
.field('isAdmin')
.required()
.type('boolean')
.mustBeFalse() // The field must be false
.done()
.build();
Validating an Object
Create a Validator
instance with your schema and validate objects against it.
const validator = new Validator(userSchema);
const user = {
isActive: true,
isAdmin: false,
};
const result = validator.validate(user);
console.log(result); // { isValid: true, errors: {} }
// Example with errors
const invalidUser = {
isActive: false, // This should be true
isAdmin: true, // This should be false
};
const invalidResult = validator.validate(invalidUser);
console.log(invalidResult);
/*
{
isValid: false,
errors: {
isActive: 'isActive must be true.',
isAdmin: 'isAdmin must be false.',
}
}
*/
API Documentation
Validator
constructor(schema: ValidationSchema)
Creates a new Validator
instance with the provided validation schema.
- Parameters:
schema
: An object defining the validation rules.
validate(obj: any): ValidationResult
Validates an object against the defined schema.
Parameters:
obj
: The object to validate.
Returns: A
ValidationResult
object containing:isValid
:boolean
indicating if the object passed validation.errors
: An object mapping field names to error messages.
SchemaBuilder
field(fieldName: string): FieldBuilder
Starts the definition of a new field in the schema.
- Parameters:
fieldName
: The name of the field to validate.
build(): ValidationSchema
Builds and returns the complete validation schema.
FieldBuilder
Provides a fluent API to define validation rules for a specific field.
required(): FieldBuilder
Marks the field as required.
type(type: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'date'): FieldBuilder
Defines the type of the field.
mustBeTrue(): FieldBuilder
Enforces that the boolean field must be true
.
mustBeFalse(): FieldBuilder
Enforces that the boolean field must be false
.
minLength(length: number): FieldBuilder
Sets the minimum length for string fields.
maxLength(length: number): FieldBuilder
Sets the maximum length for string fields.
pattern(regex: RegExp): FieldBuilder
Enforces a regex pattern on string fields.
enum(values: string[]): FieldBuilder
Restricts string fields to specific allowed values.
min(value: number): FieldBuilder
Sets the minimum value for number fields.
max(value: number): FieldBuilder
Sets the maximum value for number fields.
integer(): FieldBuilder
Ensures that the number field is an integer.
minItems(count: number): FieldBuilder
Sets the minimum number of items for array fields.
maxItems(count: number): FieldBuilder
Sets the maximum number of items for array fields.
uniqueItems(): FieldBuilder
Ensures all items in an array are unique.
items(schema: ValidationRule): FieldBuilder
Defines the validation schema for items within an array.
schema(nestedSchema: ValidationSchema): FieldBuilder
Defines a nested validation schema for object fields.
before(date: Date): FieldBuilder
Ensures that a date field is before the specified date.
after(date: Date): FieldBuilder
Ensures that a date field is after the specified date.
custom(validator: ValidatorFunction): FieldBuilder
Attaches a custom validation function to the field.
done(): SchemaBuilder
Finalizes the field definition and returns the SchemaBuilder
instance for chaining.
Examples
Basic Usage
Validating simple boolean fields:
import { Validator, SchemaBuilder } from 'biz-dynamic-object-validator';
const schemaBuilder = new SchemaBuilder();
const statusSchema = schemaBuilder
.field('isActive')
.required()
.type('boolean')
.mustBeTrue()
.done()
.build();
const validator = new Validator(statusSchema);
const result = validator.validate({ isActive: true });
console.log(result.isValid); // true
Advanced Usage
You can validate complex data structures using nested schemas and arrays:
const schema = schemaBuilder
.field('name')
.required()
.type('string')
.minLength(3)
.maxLength(50)
.done()
.field('age')
.required()
.type('number')
.min(18)
.max(65)
.integer()
.done()
.field('roles')
.type('array')
.minItems(1)
.maxItems(5)
.items(
new SchemaBuilder().field('role').type('string').enum(['admin', 'user', 'guest']).done().build()
)
.done()
.build();
Nested Object Validation
const nestedSchema = schemaBuilder
.field('address')
.schema(
new SchemaBuilder()
.field('street')
.required()
.type('string')
.done()
.field('city')
.required()
.type('string')
.done()
.build()
)
.done()
.build();
Array Validation
const arraySchema = schemaBuilder
.field('tags')
.type('array')
.minItems(1)
.maxItems(10)
.uniqueItems()
.items(new SchemaBuilder().field('tag').type('string').done().build())
.done()
.build();
Date Validation
const dateSchema = schemaBuilder
.field('startDate')
.type('date')
.after(new Date('2024-01-01'))
.done()
.field('endDate')
.type('date')
.before(new Date('2025-01-01'))
.done()
.build();
Custom Validation Functions
const customSchema = schemaBuilder
.field('email')
.type('string')
.custom((value) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(value) ? null : 'Invalid email format';
})
.done()
.build();
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
Special thanks to the open-source community for their inspiration and contributions.