b-validate

1.5.3 · active · verified Sun Apr 19

b-validate is a JavaScript and TypeScript validation library offering a flexible, chainable API for data validation. It supports basic type and value checks, as well as complex schema-based validation for objects, including asynchronous validation logic. Since its rewrite in TypeScript in version 1.4.0, it ships with robust type definitions. The library is currently stable at version 1.5.3, with releases occurring periodically to address bugs and introduce minor enhancements rather than a fixed cadence. Key differentiators include its fluent, chainable API for individual validations, comprehensive schema validation capabilities, support for custom synchronous and asynchronous validators, and granular control over validation messages, including global configuration and locale-specific message templates. It aims to provide a comprehensive validation solution for both simple and complex data structures in web and Node.js environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both basic chainable validation and complex schema validation, including custom and asynchronous validators, and optional locale loading for validation messages.

import bv, { Schema } from 'b-validate';
import zhCN from 'b-validate/es/locale/zh-CN'; // Example for locale

// --- Basic Chained Validation ---
console.log('--- Basic Chained Validation ---');
bv(123)
  .number.min(2)
  .max(10)
  .collect((error) => {
    console.log('Basic validation error:', error); // { value: 123, type: 'number', message: '123 is not less than 10' }
  });

const errorString = bv('b-validate').string.isRequired.match(/Validator/).end;
console.log('String validation error:', errorString); // { value: 'b-validate', type: 'string', message: '`b-validate` is not match pattern /Validator/' }

// --- Schema Validation ---
console.log('\n--- Schema Validation ---');
const userSchema = new Schema({
  name: [
    { type: 'string', required: true, message: 'Name is required' },
    { type: 'string', maxLength: 10, message: 'Max length is 10' },
  ],
  age: [
    { type: 'number', min: 2, max: 5, message: 'Age must be between 2 and 5' },
  ],
  email: [{ type: 'email', message: 'Invalid email format' }],
  custom: [
    {
      validator: (value, callback) => {
        if (value > 10) {
          callback('Custom value cannot be greater than 10!');
        }
      },
    },
  ],
  asyncField: [
    {
      validator: async (value, callback) => {
        // Simulate async operation
        await new Promise(resolve => setTimeout(resolve, 10));
        if (value !== 'async-ok') {
          callback('Async field must be "async-ok"');
        }
      },
    },
  ],
});

// Load a locale (optional)
userSchema.messages(zhCN);

userSchema.validate(
  {
    name: 'John Doe The Third', // Too long
    age: 24, // Out of range
    email: 'invalid-email',
    custom: 15, // Fails custom validation
    asyncField: 'not-ok'
  },
  (errors) => {
    console.log('Schema validation errors:', errors);
    /* Expected output (simplified):
     * {
     *   name: { message: 'Max length is 10' },
     *   age: { message: 'Age must be between 2 and 5' },
     *   email: { message: 'Invalid email format' },
     *   custom: { message: 'Custom value cannot be greater than 10!' },
     *   asyncField: { message: 'Async field must be "async-ok"' }
     * }
     */
  }
);

view raw JSON →