npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

biz-dynamic-object-validator

v1.0.0

Published

A Node.js package for dynamically validating objects using TypeScript.

Downloads

9

Readme

Biz Dynamic Object Validator

npm License Build

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

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.