v8n: Fluent JavaScript Validation

1.5.1 · active · verified Sun Apr 19

v8n (validation) is a JavaScript validation library offering a dead-simple, fluent API for creating complex validation rules. It supports chaining multiple rules and modifiers, allowing for highly intuitive and readable validation logic for various data types including primitives, arrays, and objects. The library provides flexible validation strategies, including boolean-based `test()`, exception-based `check()` for detailed error feedback, and `testAll()` to gather all failures, as well as asynchronous validation. Currently at version 1.5.1, v8n maintains an active development pace with incremental feature additions and bug fixes, often addressing issues related to its schema, optional, and async validation capabilities. It differentiates itself through its highly customizable nature, enabling users to extend it with custom rules, and its reusability, allowing validation chains to be exported as modules.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic string, array, object schema validation, custom rule extension, and exception-based error handling using the fluent API.

import v8n, { ValidationError } from 'v8n';

// Basic string validation
const isGreeting = v8n().string().minLength(5).first('H').last('o');
console.log('"Hello" is a greeting:', isGreeting.test('Hello')); // true

// Array and number validation with modifiers
const allEvenAndPositive = v8n().array().every.number().not.some.negative();
console.log('[2, 4, 6] are all even and positive:', allEvenAndPositive.test([2, 4, 6])); // true
console.log('[1, 2, -3] are all even and positive:', allEvenAndPositive.test([1, 2, -3])); // false

// Object schema validation
const userSchema = v8n().schema({
  id: v8n().string().alphanumeric().minLength(4),
  age: v8n().number().between(18, 99).optional()
});
console.log('Valid user object:', userSchema.test({ id: 'user123', age: 30 })); // true
console.log('Invalid user object:', userSchema.test({ id: 'abc' })); // false

// Exception-based validation
try {
  v8n().string().first('b').check('foo');
} catch (ex) {
  if (ex instanceof ValidationError) {
    console.log('Validation failed for rule:', ex.rule.name); // first
  }
}

// Custom rule extension
function isBar() {
  return value => value === 'bar';
}
v8n.extend({ isBar });
console.log('"bar" is "bar":', v8n().string().isBar().test('bar')); // true

view raw JSON →