b-validate
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
-
TypeError: bv is not a function
cause Attempting to use `require('b-validate')` to import the default export `bv` in an environment that expects ESM default imports, or trying to use `new Schema()` without destructuring.fixUse ESM import syntax: `import bv, { Schema } from 'b-validate';`. If stuck with CommonJS, some bundlers might allow `const bv = require('b-validate').default;` but it's not officially supported for all entry points. -
Error: [Object object] or message: '[Object Object]' in validation output
cause In versions prior to 1.3.4, custom validator callbacks might display `[Object Object]` if the error message passed to `callback` was not a simple string.fixUpgrade `b-validate` to version 1.3.4 or higher. If upgrading is not feasible, ensure that any custom `callback` function always receives a string as its argument for the error message. -
Cannot find module 'b-validate/es/locale/zh-CN' (or similar locale path)
cause This usually occurs when using a CommonJS environment or a bundler that doesn't correctly resolve the 'exports' field in `package.json` for ESM-specific paths, particularly for locale files which are directly under `es/locale`.fixEnsure your bundler (e.g., Webpack, Rollup) is configured to handle ESM modules and resolve package `exports`. If using Node.js directly, ensure you are running in an ESM context. You might need to adjust import paths or configure your bundler to alias the `es` path.
Warnings
- breaking Version 1.4.0 involved a complete rewrite in TypeScript. While the public API aimed for backward compatibility, internal changes or specific bundler configurations might reveal issues for users relying on older CommonJS-specific behaviors or undocumented internals.
- gotcha Custom validator callbacks in versions prior to 1.3.4 could incorrectly display `[Object Object]` as the error message if the parameter was an object. This was fixed to correctly reflect the message provided.
- gotcha When customizing validation messages, be aware of the precedence: `options.validateMessages` passed to `bv()` or `new Schema()` takes precedence over `(new schema({})).messages()` which in turn takes precedence over global configuration set by `bv.setGlobalConfig({ validateMessages: {} })`.
Install
-
npm install b-validate -
yarn add b-validate -
pnpm add b-validate
Imports
- bv
const bv = require('b-validate');import bv from 'b-validate';
- Schema
const { Schema } = require('b-validate');import { Schema } from 'b-validate'; - zhCN (locale)
import zhCN from 'b-validate/locale/zh-CN';
import zhCN from 'b-validate/es/locale/zh-CN';
Quickstart
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"' }
* }
*/
}
);