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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ticatec/bean-validator

v0.1.0

Published

A flexible and powerful validation library for Node.js that allows you to validate JavaScript objects through rule-based validation.

Downloads

91

Readme

Bean Validator

Version License: MIT

A flexible and powerful validation library for Node.js that allows you to validate JavaScript objects through rule-based validation.

中文文档 | English

Installation

npm i @ticatec/bean-validator

Quick Start

import beanValidator from "@ticatec/bean-validator";
import {BaseValidator, StringValidator, NumberValidator, DateValidator, EnumValidator, ObjectValidator, ArrayValidator} from "@ticatec/bean-validator";

// Define validation rules
let rules: Array<BaseValidator> = [
    new StringValidator('name', {required: true, maxLen: 50}),
    new NumberValidator('age', {required: true, minValue: 0, maxValue: 120}),
    new EnumValidator('gender', {values: ['M', 'F', 'Other']})
];

// Data to validate
let data = {
    name: 'John Doe',
    age: 30,
    gender: 'M'
};

// Perform validation
let result = beanValidator.validate(data, rules);

if (result.valid) {
    console.log('Validation passed!');
} else {
    console.log('Validation errors:', result.errorMessage);
}

Validators

StringValidator

Validates string values with support for length constraints and format validation.

Constructor

interface StringValidatorOptions extends ValidatorOptions {
    minLen?: number,     // Minimum length
    maxLen?: number,     // Maximum length
    format?: {
        regex: RegExp,   // Regular expression for format validation
        message: string  // Error message when format validation fails
    }
}

new StringValidator(field: string, options?: StringValidatorOptions);

Example

new StringValidator('email', {
    required: true,
    maxLen: 100,
    format: {
        regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
        message: 'Invalid email format'
    }
});

NumberValidator

Validates numeric values with range constraints and automatic type conversion.

Constructor

interface NumberValidatorOptions extends ValidatorOptions {
    minValue?: number,   // Minimum value
    maxValue?: number,   // Maximum value
}

new NumberValidator(field: string, options?: NumberValidatorOptions);

Example

new NumberValidator('age', {
    required: true,
    minValue: 0,
    maxValue: 120
});

DateValidator

Validates date values with support for date ranges and relative date constraints.

Constructor

interface DateValidatorOptions extends ValidatorOptions {
    from?: Date,              // Earliest allowed date
    to?: Date,                // Latest allowed date
    maxDaysBefore?: number,   // Maximum days before today
    maxDaysAfter?: number,    // Maximum days after today
}

new DateValidator(field: string, options?: DateValidatorOptions);

Example

new DateValidator('birthDate', {
    required: true,
    maxDaysBefore: 36500  // Allow dates up to 100 years ago
});

EnumValidator

Validates that a value exists within a predefined set of allowed values.

Constructor

interface EnumValidatorOptions extends ValidatorOptions {
    values: Array<any>;  // Array of allowed values
}

new EnumValidator(field: string, options: EnumValidatorOptions);

Example

new EnumValidator('status', {
    required: true,
    values: ['active', 'inactive', 'pending']
});

BooleanValidator

Validates boolean values with automatic type conversion.

Constructor

interface BooleanValidatorOptions extends ValidatorOptions {
    // No additional options beyond base ValidatorOptions
}

new BooleanValidator(field: string, options?: BooleanValidatorOptions);

ObjectValidator

Validates nested objects by applying a set of validation rules to the object's properties.

Constructor

interface ObjectValidatorOptions extends ValidatorOptions {
    rules: Array<BaseValidator>;  // Validation rules for the nested object
}

new ObjectValidator(field: string, options: ObjectValidatorOptions);

Example

let addressRules = [
    new StringValidator('street', {required: true, maxLen: 100}),
    new StringValidator('city', {required: true, maxLen: 50}),
    new StringValidator('zipCode', {required: true, maxLen: 10})
];

new ObjectValidator('address', {
    required: true,
    rules: addressRules
});

ArrayValidator

Validates arrays with support for length constraints and element validation.

Constructor

interface ArrayValidatorOptions extends ValidatorOptions {
    rules?: Array<BaseValidator>;  // Validation rules for array elements
    minLen?: number;               // Minimum array length
    maxLen?: number;               // Maximum array length
}

new ArrayValidator(field: string, options?: ArrayValidatorOptions);

Example

let itemRules = [
    new StringValidator('name', {required: true}),
    new NumberValidator('quantity', {required: true, minValue: 1})
];

new ArrayValidator('items', {
    required: true,
    minLen: 1,
    maxLen: 10,
    rules: itemRules
});

Common Options

All validators extend from BaseValidator and support these common options:

interface ValidatorOptions {
    required?: boolean;           // Whether the field is required
    check?: CustomCheck;          // Custom validation function
}

type CustomCheck = (value: any, data: any, prefix: string) => string | null;

Custom Validation

You can add custom validation logic using the check option:

new StringValidator('username', {
    required: true,
    minLen: 3,
    maxLen: 20,
    check: (value, data, prefix) => {
        if (value.includes(' ')) {
            return 'Username cannot contain spaces';
        }
        return null; // null means validation passed
    }
});

Advanced Features

Nested Field Access

The library supports dot notation for accessing nested properties:

new StringValidator('user.profile.name', {required: true});

Type Conversion

The library automatically converts compatible types:

  • String numbers to actual numbers in NumberValidator
  • String representations to proper types where applicable

Error Handling

Validation results provide detailed error information:

let result = beanValidator.validate(data, rules);

if (!result.valid) {
    console.log('All errors:', result.errorMessage);
    // Errors are joined with newlines
}

Complete Example

import beanValidator from "@ticatec/bean-validator";
import {BaseValidator, StringValidator, NumberValidator, DateValidator, EnumValidator, ObjectValidator, ArrayValidator} from "@ticatec/bean-validator";

// Define rules for member object
let memberRules: Array<BaseValidator> = [
    new DateValidator('registerOn', {maxDaysAfter: -5}),
    new StringValidator('password', {
        required: true,
        format: {
            regex: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,}$/,
            message: 'Password must be at least 8 characters with uppercase, lowercase and numbers'
        }
    })
];

// Define main validation rules
let rules: Array<BaseValidator> = [
    new StringValidator('name', {required: true, maxLen: 50}),
    new NumberValidator('age', {required: true, maxValue: 90, minValue: 15}),
    new DateValidator('dob', {maxDaysBefore: 100000}),
    new EnumValidator('gender', {values: ['F', 'M']}),
    new ObjectValidator('member', {rules: memberRules})
];

// Rules for parent with children
let parentRules: Array<BaseValidator> = [
    ...rules,
    new ArrayValidator('children', {required: true, rules: rules})
];

let data = {
    name: 'John Doe',
    age: 35,
    dob: '1988-03-05',
    gender: 'M',
    member: {
        registerOn: new Date('2023-01-01'),
        password: 'SecurePass123'
    },
    children: [
        {
            name: 'Jane',
            age: 16,
            dob: '2007-08-12',
            gender: 'F',
            member: {
                registerOn: new Date('2023-06-01'),
                password: 'ChildPass456'
            }
        }
    ]
};

let result = beanValidator.validate(data, parentRules);

if (result.valid) {
    console.log('All validations passed!');
    console.log('Validated data:', data);
} else {
    console.log('Validation errors:');
    console.log(result.errorMessage);
}

License

MIT

Repository

  • GitHub: https://github.com/ticatec/node-library
  • Issues: https://github.com/ticatec/bean-validator/issues

Author

Henry Feng