{"id":10534,"library":"b-validate","title":"b-validate","description":"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.","status":"active","version":"1.5.3","language":"javascript","source_language":"en","source_url":"https://github.com/PengJiyuan/b-validate","tags":["javascript","validate","type","typescript"],"install":[{"cmd":"npm install b-validate","lang":"bash","label":"npm"},{"cmd":"yarn add b-validate","lang":"bash","label":"yarn"},{"cmd":"pnpm add b-validate","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary entry point for chained validation. While CommonJS `require` might work with transpilation, ESM `import` is the recommended and type-safe approach, especially since v1.4.0's TypeScript rewrite.","wrong":"const bv = require('b-validate');","symbol":"bv","correct":"import bv from 'b-validate';"},{"note":"Used for object schema validation. This is a named export, unlike `bv` which is a default export. Ensure correct destructuring.","wrong":"const { Schema } = require('b-validate');","symbol":"Schema","correct":"import { Schema } from 'b-validate';"},{"note":"Locale files are exposed directly from the `es/locale` path. The `es` directory indicates the ESM build output. Adjust path if using a CJS-only bundler that doesn't resolve 'exports' map correctly.","wrong":"import zhCN from 'b-validate/locale/zh-CN';","symbol":"zhCN (locale)","correct":"import zhCN from 'b-validate/es/locale/zh-CN';"}],"quickstart":{"code":"import bv, { Schema } from 'b-validate';\nimport zhCN from 'b-validate/es/locale/zh-CN'; // Example for locale\n\n// --- Basic Chained Validation ---\nconsole.log('--- Basic Chained Validation ---');\nbv(123)\n  .number.min(2)\n  .max(10)\n  .collect((error) => {\n    console.log('Basic validation error:', error); // { value: 123, type: 'number', message: '123 is not less than 10' }\n  });\n\nconst errorString = bv('b-validate').string.isRequired.match(/Validator/).end;\nconsole.log('String validation error:', errorString); // { value: 'b-validate', type: 'string', message: '`b-validate` is not match pattern /Validator/' }\n\n// --- Schema Validation ---\nconsole.log('\\n--- Schema Validation ---');\nconst userSchema = new Schema({\n  name: [\n    { type: 'string', required: true, message: 'Name is required' },\n    { type: 'string', maxLength: 10, message: 'Max length is 10' },\n  ],\n  age: [\n    { type: 'number', min: 2, max: 5, message: 'Age must be between 2 and 5' },\n  ],\n  email: [{ type: 'email', message: 'Invalid email format' }],\n  custom: [\n    {\n      validator: (value, callback) => {\n        if (value > 10) {\n          callback('Custom value cannot be greater than 10!');\n        }\n      },\n    },\n  ],\n  asyncField: [\n    {\n      validator: async (value, callback) => {\n        // Simulate async operation\n        await new Promise(resolve => setTimeout(resolve, 10));\n        if (value !== 'async-ok') {\n          callback('Async field must be \"async-ok\"');\n        }\n      },\n    },\n  ],\n});\n\n// Load a locale (optional)\nuserSchema.messages(zhCN);\n\nuserSchema.validate(\n  {\n    name: 'John Doe The Third', // Too long\n    age: 24, // Out of range\n    email: 'invalid-email',\n    custom: 15, // Fails custom validation\n    asyncField: 'not-ok'\n  },\n  (errors) => {\n    console.log('Schema validation errors:', errors);\n    /* Expected output (simplified):\n     * {\n     *   name: { message: 'Max length is 10' },\n     *   age: { message: 'Age must be between 2 and 5' },\n     *   email: { message: 'Invalid email format' },\n     *   custom: { message: 'Custom value cannot be greater than 10!' },\n     *   asyncField: { message: 'Async field must be \"async-ok\"' }\n     * }\n     */\n  }\n);","lang":"typescript","description":"This quickstart demonstrates both basic chainable validation and complex schema validation, including custom and asynchronous validators, and optional locale loading for validation messages."},"warnings":[{"fix":"Ensure your build tooling correctly handles TypeScript output and ESM imports. If experiencing issues, verify import paths and how your bundler resolves the 'exports' field in package.json.","message":"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.","severity":"breaking","affected_versions":">=1.4.0"},{"fix":"Upgrade to version 1.3.4 or later to ensure custom validator messages are displayed correctly. If an upgrade is not possible, ensure your `callback` function is always called with a string message.","message":"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.","severity":"gotcha","affected_versions":"<1.3.4"},{"fix":"Always test your message customization in the context you intend. For highly localized or specific messages, prefer passing options directly to the validator instance or schema. Use global config for application-wide defaults.","message":"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: {} })`.","severity":"gotcha","affected_versions":">=1.4.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use 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.","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.","error":"TypeError: bv is not a function"},{"fix":"Upgrade `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.","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.","error":"Error: [Object object] or message: '[Object Object]' in validation output"},{"fix":"Ensure 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.","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`.","error":"Cannot find module 'b-validate/es/locale/zh-CN' (or similar locale path)"}],"ecosystem":"npm"}