VineJS Documentation

repository·4.x·Indexed 23 days ago

https://github.com/vinejs/vine

A high-performance form data validation library for Node.js, optimized for validating HTTP request bodies in backend applications. It provides type safety and a comprehensive set of schema types including primitives, complex types like objects and arrays, and specialized types for checkboxes and any-value inputs. Features include support for nullable and optional fields, custom validation rules via .use(), input transformation with .parse(), and the ability to export schemas to JSON Schema7.

Tokens
12.2K
Snippets
54
Records
91
Agent score
75%

What's inside VineJS

  1. Overview of VineJS

    4.x
    VineJS is a high-performance form data validation library designed for Node.js. It is primarily used to validate HTTP request bodies in backend applications, offering high speed and type safety.
  2. Run VineJS benchmarks locally

    4.x

    To run the performance benchmarks on your local machine, you must first build the project and then execute the specific benchmark script from the build directory. The benchmarks cover various scenarios including flat objects, nested objects, arrays, and unions.

    # Example for running the flat object benchmark
    npm run build
    node build/benchmarks/flat_object.js
  3. Use `unionOfTypes` to automatically detect schema types

    4.x

    unionOfTypes represents a union data type that automatically determines which schema to apply based on the value's type. Unlike regular unions that require explicit conditionals, it uses each schema's IS_OF_TYPE method to detect the appropriate schema based on the input value's type.

    Common use cases include:

    • Matching primitive types (e.g., string, number, boolean).
    • Matching object structures (e.g., a user object vs an admin object based on a type literal field).
    // Example 1: Primitive types
    const schema = vine.unionOfTypes([
      vine.string(),
      vine.number(),
      vine.boolean()
    ])
    
    // Example 2: Object structures
    const schema = vine.unionOfTypes([
      vine.object({ type: vine.literal('user'), name: vine.string() }),
      vine.object({ type: vine.literal('admin'), permissions: vine.array(vine.string()) })
    ])
  4. Use Vine union for conditional validation

    4.x

    A VineUnion represents a union data type where different schemas are applied based on runtime conditions. The union evaluates an array of conditionals in order; the first condition that matches the input value determines which schema is used for validation.

    To create a union, pass an array of conditional branches (such as those created via vine.union.if() or vine.union.else()) to the constructor.

    If no conditions match, you can define a custom fallback behavior using the .otherwise() method to report a specific error.

    const schema = vine.object({
      userType: vine.string(),
      data: vine.union([
        vine.union.if(
          (value) => value.userType === 'admin',
          vine.object({ permissions: vine.array(vine.string()) })
        ),
        vine.union.else(
          vine.object({ role: vine.string() })
        )
      ])
    })
  5. Standard Schema V1 compliance

    4.x
    The VineValidator implements the StandardSchemaV1 specification, allowing it to interoperate with other libraries that support this standard. It provides a ~standard property that includes validate and jsonSchema implementations. Note that while it can provide a JSON Schema for input, it does not currently support creating validators from an existing JSON Schema.
  6. How metadata validation works with withMetaData()

    4.x

    The withMetaData<MetaData>() method allows you to pass additional runtime context (like user IDs or permissions) to your validation rules. You can provide an optional callback to validate this metadata before the main data validation occurs.

    This returns a builder that you then use to call .create(schema).

    // Without metadata validation
    const validate = vine.withMetaData<{ userId: string }>().create({
      title: vine.string(),
      description: vine.string()
    })
    
    await validate.validate(data, { meta: { userId: '123' } })
    
    // With metadata validation (validating the meta object itself)
    const validate = vine
      .withMetaData<{ userId: string }>((meta) => {
        if (!meta.userId) {
          throw new Error('userId is required in metadata')
        }
      })
      .create(schema)
    
    await validate.validate(data, { meta: { userId: '123' } })
  7. Use VineRecord for validating objects with dynamic keys

    4.x

    VineRecord represents an object with dynamic keys where every value must adhere to the same schema. Unlike VineObject, which requires predefined property names, VineRecord allows any string key but enforces consistent value types across all of them.

    You can create a record schema by passing a schema to vine.record(). This is useful for maps, dictionaries, or any object where the keys are unknown or arbitrary but the values follow a specific structure.

    Examples

    Basic record with primitive values:

    const schema = vine.record(vine.number())
    
    const result = await vine.validate({
      schema,
      data: { a: 1, b: 2, c: 3 }
    })

    Record with complex object values:

    const schema = vine.record(
      vine.object({
        name: vine.string(),
        age: vine.number()
      })
    )
    const schema = vine.record(vine.number())
    
    const result = await vine.validate({
      schema,
      data: { a: 1, b: 2, c: 3 }
    })
  8. Use the VineDate schema for date validation

    4.x

    The VineDate schema is used to validate and parse values (strings or numbers) into JavaScript Date objects. It supports various date formats and provides a wide range of comparison rules, such as checking if a date is after, before, or equal to another date or field.

    Basic usage:

    const schema = vine.date()
      .after('today')
      .before('2025-12-31')
    
    const result = await vine.validate({
      schema,
      data: '2025-06-15'
    })
  9. Benchmark unions

    4.x

    The union benchmark measures performance when validating schema unions. The source code for this benchmark is located in ./benchmarks/union.ts.

    Note: Yup does not support unions, so it is excluded from this specific benchmark.

    npm run build
    node build/benchmarks/union.js
  10. Benchmark nested objects

    4.x

    The nested object benchmark measures performance when validating objects with multiple levels of depth. The source code for this benchmark is located in ./benchmarks/nested_object.ts.

    npm run build
    node build/benchmarks/nested_object.js
  11. Benchmark flat objects

    4.x

    The flat object benchmark measures performance when validating a single-level object. The source code for this benchmark is located in ./benchmarks/flat_object.ts.

    npm run build
    node build/benchmarks/flat_object.js