@vinejs/vine - v4.0.0-next.1
    Preparing search index...

    Class Vine

    Main Vine class that provides a fluent API for creating validation schemas and validating user input with type-safety using pre-compiled schemas.

    const vine = new Vine()
    const schema = vine.object({
    name: vine.string(),
    age: vine.number()
    })
    const result = await vine.validate({ schema, data: { name: 'John', age: 30 } })

    Hierarchy (View Summary)

    Index

    Constructors

    • Constructor that applies all registered instance properties to the new instance. This method iterates through the instanceMacros set and assigns each property to the instance, binding functions to the instance context.

      Returns Vine

    Properties

    group: typeof group = group

    Define a sub-object as a conditional union group. Groups allow creating conditional validations based on discriminator fields.

    vine.group([
    vine.group.if(vine.string(), vine.object({ name: vine.string() }))
    ])
    union: typeof union = union

    Define a union of multiple schema types. Union schemas attempt to validate against each schema until one succeeds.

    vine.union([
    vine.string(),
    vine.number()
    ])
    messagesProvider: MessagesProviderContact = ...

    Messages provider to use on the validator for internationalization and custom error message formatting

    errorReporter: () => ErrorReporterContract = ...

    Error reporter factory function to use on the validator for formatting validation errors

    convertEmptyStringsToNull: boolean = false

    Control whether or not to convert empty strings to null during validation. Useful for HTML form handling where empty inputs are submitted as empty strings

    helpers: {
        exists(value: any): boolean;
        isMissing(value: any): boolean;
        isTrue(value: any): boolean;
        isFalse(value: any): boolean;
        isString(value: unknown): value is string;
        isObject<Value>(value: unknown): value is Record<PropertyKey, Value>;
        hasKeys(value: Record<string, any>, keys: string[]): boolean;
        isArray<Value>(value: unknown): value is Value[];
        isNumeric(value: any): boolean;
        asNumber(value: any): number;
        asBoolean(value: any): boolean | null;
        asDayJS(
            value: any,
            format: OptionType | undefined,
        ): { dateTime: Dayjs; formats: string | string[] | FormatObject };
        compareValues(
            inputValue: unknown,
            expectedValue: any,
        ): { isEqual: boolean; casted: unknown };
        isEmail: (str: string, options?: IsEmailOptions) => boolean;
        isURL: (str: string, options?: IsURLOptions) => boolean;
        isAlpha: (
            str: string,
            locale?: AlphaLocale,
            options?: IsAlphaOptions,
        ) => boolean;
        isAlphaNumeric: (
            str: string,
            locale?: AlphanumericLocale,
            options?: IsAlphanumericOptions,
        ) => boolean;
        isIP: (str: string, version?: IPVersion) => boolean;
        isUUID: (str: string, version?: UUIDVersion) => boolean;
        isAscii: (str: string) => boolean;
        isCreditCard: (str: string, options?: IsCreditCardOptions) => boolean;
        isIBAN: (str: string, options?: IsIBANOptions) => boolean;
        isJWT: (str: string) => boolean;
        isLatLong: (str: string) => boolean;
        isMobilePhone: (
            str: string,
            locale?: MobilePhoneLocale | MobilePhoneLocale[] | "any",
            options?: IsMobilePhoneOptions,
        ) => boolean;
        isPassportNumber: (str: string, countryCode?: string) => boolean;
        isPostalCode: (str: string, locale: PostalCodeLocale | "any") => boolean;
        isSlug: (str: string) => boolean;
        isDecimal: (str: string, options?: IsDecimalOptions) => boolean;
        mobileLocales: MobilePhoneLocale[];
        postalCountryCodes: PostalCodeLocale[];
        passportCountryCodes: readonly [
            "AM",
            "AR",
            "AT",
            "AU",
            "AZ",
            "BE",
            "BG",
            "BR",
            "BY",
            "CA",
            "CH",
            "CY",
            "CZ",
            "DE",
            "DK",
            "DZ",
            "ES",
            "FI",
            "FR",
            "GB",
            "GR",
            "HR",
            "HU",
            "IE",
            "IN",
            "ID",
            "IR",
            "IS",
            "IT",
            "JM",
            "JP",
            "KR",
            "KZ",
            "LI",
            "LT",
            "LU",
            "LV",
            "LY",
            "MT",
            "MZ",
            "MY",
            "MX",
            "NL",
            "NZ",
            "PH",
            "PK",
            "PL",
            "PT",
            "RO",
            "RU",
            "SE",
            "SL",
            "SK",
            "TH",
            "TR",
            "UA",
            "US",
        ];
        isULID(value: unknown): boolean;
        isHexColor: (value: string) => boolean;
        isActiveURL: (url: string) => Promise<boolean>;
        isDistinct: (dataSet: any[], fields?: string | string[]) => boolean;
        getNestedValue(key: string, field: FieldContext): any;
    } = helpers

    Collection of helper functions to perform type-checking or cast types while keeping HTML forms serialization behavior in mind

    Type Declaration

    • exists: function
      • Checks if a value exists (is not null and not undefined). Useful for checking if optional form fields have been provided.

        Parameters

        • value: any

          The value to check

        Returns boolean

        True if value is not null and not undefined

        helpers.exists('hello') // true
        helpers.exists(0) // true
        helpers.exists(null) // false
        helpers.exists(undefined) // false
    • isMissing: function
      • Checks if a value is missing (null or undefined). The inverse of the exists method.

        Parameters

        • value: any

          The value to check

        Returns boolean

        True if value is null or undefined

        helpers.isMissing(null) // true
        helpers.isMissing(undefined) // true
        helpers.isMissing('') // false
        helpers.isMissing(0) // false
    • isTrue: function
      • Checks if a value represents a truthy boolean in HTML form context. Recognizes common HTML form representations of true values.

        Accepted truthy values:

        • true (boolean)
        • 1 (number)
        • "1" (string)
        • "true" (string)
        • "on" (string, for checkboxes)

        Parameters

        • value: any

          The value to check

        Returns boolean

        True if value represents a truthy boolean

        helpers.isTrue(true) // true
        helpers.isTrue('on') // true (checkbox checked)
        helpers.isTrue('1') // true (form input)
        helpers.isTrue('yes') // false
    • isFalse: function
      • Checks if a value represents a falsy boolean in HTML form context. Recognizes common HTML form representations of false values.

        Accepted falsy values:

        • false (boolean)
        • 0 (number)
        • "0" (string)
        • "false" (string)

        Parameters

        • value: any

          The value to check

        Returns boolean

        True if value represents a falsy boolean

        helpers.isFalse(false) // true
        helpers.isFalse('0') // true (form input)
        helpers.isFalse('false') // true (form input)
        helpers.isFalse('no') // false
    • isString: function
      • Type guard that checks if a value is a string. Narrows the TypeScript type to string when returning true.

        Parameters

        • value: unknown

          The value to check

        Returns value is string

        True if value is a string, with type narrowing

        if (helpers.isString(value)) {
        // value is now typed as string
        console.log(value.toUpperCase())
        }
    • isObject: function
      • Type guard that checks if a value is a plain JavaScript object. Excludes null, arrays, and other non-plain objects.

        Type Parameters

        • Value

          The type of values in the object

        Parameters

        • value: unknown

          The value to check

        Returns value is Record<PropertyKey, Value>

        True if value is a plain object, with type narrowing

        helpers.isObject({}) // true
        helpers.isObject([]) // false
        helpers.isObject(null) // false
        helpers.isObject(new Date()) // true (but not recommended for validation)
    • hasKeys: function
      • Checks if an object contains all the specified keys. Useful for validating object structure before processing.

        Parameters

        • value: Record<string, any>

          The object to check

        • keys: string[]

          Array of key names that must exist

        Returns boolean

        True if all keys exist in the object

        helpers.hasKeys({ name: 'John', age: 30 }, ['name']) // true
        helpers.hasKeys({ name: 'John' }, ['name', 'age']) // false
    • isArray: function
      • Type guard that checks if a value is an array. Narrows the TypeScript type to array when returning true.

        Type Parameters

        • Value

          The type of elements in the array

        Parameters

        • value: unknown

          The value to check

        Returns value is Value[]

        True if value is an array, with type narrowing

        if (helpers.isArray(value)) {
        // value is now typed as array
        console.log(value.length)
        }
    • isNumeric: function
      • Checks if a value is numeric (number or string representing a number). Useful for validating form inputs that should contain numeric values.

        Parameters

        • value: any

          The value to check

        Returns boolean

        True if value can be converted to a valid number

        helpers.isNumeric(42) // true
        helpers.isNumeric('42') // true
        helpers.isNumeric('42.5') // true
        helpers.isNumeric('abc') // false
    • asNumber: function
      • Converts a value to a number using JavaScript's Number() constructor. Handles null values explicitly by returning NaN.

        Parameters

        • value: any

          The value to convert to a number

        Returns number

        The numeric representation, or NaN if conversion fails

        helpers.asNumber('42') // 42
        helpers.asNumber('42.5') // 42.5
        helpers.asNumber(null) // NaN
        helpers.asNumber('abc') // NaN
    • asBoolean: function
      • Converts a value to a boolean using HTML form semantics. Returns null for values that cannot be reliably converted.

        Conversion rules:

        • [true, 1, "1", "true", "on"] → true
        • [false, 0, "0", "false"] → false
        • Everything else → null

        Parameters

        • value: any

          The value to convert

        Returns boolean | null

        Boolean value, or null if conversion is ambiguous

        helpers.asBoolean('true') // true
        helpers.asBoolean('on') // true (checkbox checked)
        helpers.asBoolean('false') // false
        helpers.asBoolean('maybe') // null (ambiguous)
    • asDayJS: function
      • Converts a value to a Day.js date object with flexible format support. Handles timestamps, ISO dates, and custom formats with intelligent fallbacks.

        Parameters

        • value: any

          The value to convert to a date (string, number, Date, etc.)

        • format: OptionType | undefined

          Date format(s) to use for parsing. Can be:

          • Array of format strings (e.g., ['YYYY-MM-DD', 'DD/MM/YYYY'])
          • Single format string
          • Object with format and strict parsing options
          • Special values: 'x' for timestamps, 'iso8601' for ISO dates

        Returns { dateTime: Dayjs; formats: string | string[] | FormatObject }

        Object containing the parsed Day.js instance and normalized formats

        // Parse with default formats
        helpers.asDayJS('2023-12-25')
        // { dateTime: dayjs('2023-12-25'), formats: ['YYYY-MM-DD', 'YYYY-MM-DD HH:mm:ss'] }

        // Parse timestamp
        helpers.asDayJS('1703548800000', ['x'])
        // { dateTime: dayjs(1703548800000), formats: ['x'] }

        // Parse with custom format
        helpers.asDayJS('25/12/2023', ['DD/MM/YYYY'])
        // { dateTime: dayjs('25/12/2023', 'DD/MM/YYYY'), formats: ['DD/MM/YYYY'] }

        // ISO date fallback
        helpers.asDayJS('2023-12-25T10:30:00Z', ['iso8601'])
        // { dateTime: dayjs('2023-12-25T10:30:00Z'), formats: ['iso8601'] }
    • compareValues: function
      • Compares two values with intelligent type coercion. The input value is cast to match the type of the expected value for HTML form-friendly comparisons.

        Parameters

        • inputValue: unknown

          The input value to compare

        • expectedValue: any

          The expected value to compare against

        Returns { isEqual: boolean; casted: unknown }

        Object with comparison result and the casted input value

        // Number comparison
        helpers.compareValues('42', 42)
        // { isEqual: true, casted: 42 }

        // Boolean comparison
        helpers.compareValues('true', true)
        // { isEqual: true, casted: true }

        // String comparison (no casting)
        helpers.compareValues('hello', 'world')
        // { isEqual: false, casted: 'hello' }
    • isEmail: (str: string, options?: IsEmailOptions) => boolean

      Validates email addresses using comprehensive rules

    • isURL: (str: string, options?: IsURLOptions) => boolean

      Validates URLs with protocol and domain checking

    • isAlpha: (str: string, locale?: AlphaLocale, options?: IsAlphaOptions) => boolean

      Validates alphabetic characters only

    • isAlphaNumeric: (
          str: string,
          locale?: AlphanumericLocale,
          options?: IsAlphanumericOptions,
      ) => boolean

      Validates alphanumeric characters only

    • isIP: (str: string, version?: IPVersion) => boolean

      Validates IP addresses (IPv4 and IPv6)

    • isUUID: (str: string, version?: UUIDVersion) => boolean

      Validates UUID strings in various formats

    • isAscii: (str: string) => boolean

      Validates ASCII character strings

    • isCreditCard: (str: string, options?: IsCreditCardOptions) => boolean

      Validates credit card numbers using Luhn algorithm

    • isIBAN: (str: string, options?: IsIBANOptions) => boolean

      Validates International Bank Account Numbers

    • isJWT: (str: string) => boolean

      Validates JSON Web Tokens

    • isLatLong: (str: string) => boolean

      Validates latitude/longitude coordinate pairs

    • isMobilePhone: (
          str: string,
          locale?: MobilePhoneLocale | MobilePhoneLocale[] | "any",
          options?: IsMobilePhoneOptions,
      ) => boolean

      Validates mobile phone numbers for various locales

    • isPassportNumber: (str: string, countryCode?: string) => boolean

      Validates passport numbers for supported countries

    • isPostalCode: (str: string, locale: PostalCodeLocale | "any") => boolean

      Validates postal codes for various countries

    • isSlug: (str: string) => boolean

      Validates URL slugs (lowercase, hyphenated strings)

    • isDecimal: (str: string, options?: IsDecimalOptions) => boolean

      Validates decimal numbers

    • mobileLocales: MobilePhoneLocale[]

      Array of supported mobile phone locales/countries

    • postalCountryCodes: PostalCodeLocale[]

      Array of supported postal code country codes

    • passportCountryCodes: readonly [
          "AM",
          "AR",
          "AT",
          "AU",
          "AZ",
          "BE",
          "BG",
          "BR",
          "BY",
          "CA",
          "CH",
          "CY",
          "CZ",
          "DE",
          "DK",
          "DZ",
          "ES",
          "FI",
          "FR",
          "GB",
          "GR",
          "HR",
          "HU",
          "IE",
          "IN",
          "ID",
          "IR",
          "IS",
          "IT",
          "JM",
          "JP",
          "KR",
          "KZ",
          "LI",
          "LT",
          "LU",
          "LV",
          "LY",
          "MT",
          "MZ",
          "MY",
          "MX",
          "NL",
          "NZ",
          "PH",
          "PK",
          "PL",
          "PT",
          "RO",
          "RU",
          "SE",
          "SL",
          "SK",
          "TH",
          "TR",
          "UA",
          "US",
      ]

      Array of supported passport country codes

    • isULID: function
      • Validates if a value is a valid ULID (Universally Unique Lexicographically Sortable Identifier). ULIDs are 26-character strings that are lexicographically sortable and URL-safe.

        Parameters

        • value: unknown

          The value to validate

        Returns boolean

        True if value is a valid ULID

        helpers.isULID('01ARZ3NDEKTSV4RRFFQ69G5FAV') // true
        helpers.isULID('invalid-ulid') // false
        helpers.isULID('7ZZZZZZZZZZZZZZZZZZZZZZZZZ') // true (max valid ULID)
        helpers.isULID('8AAAAAAAAAAAAAAAAAAAAAAAAA') // false (overflow)
    • isHexColor: (value: string) => boolean

      Validates if a value is a valid hexadecimal color code. Requires the '#' prefix and supports 3, 6, or 8 character hex codes.

      helpers.isHexColor('#FF0000') // true (red)
      helpers.isHexColor('#f00') // true (short red)
      helpers.isHexColor('#FF000080') // true (red with alpha)
      helpers.isHexColor('FF0000') // false (missing #)
      helpers.isHexColor('#GGGGGG') // false (invalid hex)
    • isActiveURL: (url: string) => Promise<boolean>

      Validates if a URL has valid DNS records (A or AAAA records). This performs an actual DNS lookup to verify the domain exists.

      await helpers.isActiveURL('https://example.com') // true
      await helpers.isActiveURL('https://nonexistent-domain-12345.com') // false

      This function requires network access and may be slow.
      Consider caching results for better performance.
    • isDistinct: (dataSet: any[], fields?: string | string[]) => boolean

      Check if all the elements inside the dataset are unique.

      In case of an array of objects, you must provide one or more keys for the fields that must be unique across the objects.

      helpers.isDistinct([1, 2, 4, 5]) // true

      // Null and undefined values are ignored
      helpers.isDistinct([1, null, 2, null, 4, 5]) // true

      helpers.isDistinct([
      {
      email: 'foo@bar.com',
      name: 'foo'
      },
      {
      email: 'baz@bar.com',
      name: 'baz'
      }
      ], 'email') // true

      helpers.isDistinct([
      {
      email: 'foo@bar.com',
      tenant_id: 1,
      name: 'foo'
      },
      {
      email: 'foo@bar.com',
      tenant_id: 2,
      name: 'baz'
      }
      ], ['email', 'tenant_id']) // true
    • getNestedValue: function
      • Retrieves a nested value from the validation context. Supports both dot notation for deep access and direct parent access.

        Parameters

        • key: string

          The key or dot-notation path to the value

        • field: FieldContext

          The field context containing data and parent references

        Returns any

        The value at the specified path, or undefined if not found

        // Dot notation for nested access
        helpers.getNestedValue('user.profile.name', field)

        // Direct parent access
        helpers.getNestedValue('confirmPassword', field)

        // Deep object access
        helpers.getNestedValue('config.database.host', field)
    createRule: <Options = undefined>(
        validator: Validator<Options>,
        metaData?: { name?: string; implicit?: boolean; isAsync?: boolean },
    ) => (...options: GetArgs<Options>) => Validation<Options> = createRule

    Utility function to convert a validation function to a Vine schema rule

    Type Declaration

      • <Options = undefined>(
            validator: Validator<Options>,
            metaData?: { name?: string; implicit?: boolean; isAsync?: boolean },
        ): (...options: GetArgs<Options>) => Validation<Options>
      • Creates a reusable validation rule from a validator function. The returned function can be applied to any schema type using the schema.use() method. Automatically detects async functions and provides proper metadata.

        Type Parameters

        • Options = undefined

          The type of options the validator accepts

        Parameters

        • validator: Validator<Options>

          The validation function to convert into a rule

        • OptionalmetaData: { name?: string; implicit?: boolean; isAsync?: boolean }

          Optional metadata about the validation rule

          • Optionalname?: string

            Custom name for the validation rule

          • Optionalimplicit?: boolean

            Whether the rule should run on null/undefined values

          • OptionalisAsync?: boolean

            Whether the validator function is async

        Returns (...options: GetArgs<Options>) => Validation<Options>

        A rule factory function that can be used with schema.use()

        // Simple validation rule
        const isEven = createRule<{ strict?: boolean }>((value, options, field) => {
        const num = Number(value)
        if (num % 2 !== 0) {
        throw new Error('Value must be even')
        }
        return value
        })

        // Usage with schema
        vine.number().use(isEven({ strict: true }))
        // Async validation rule
        const checkUnique = createRule<{ table: string }>(async (value, { table }, field) => {
        const exists = await database.exists(table, value)
        if (exists) {
        throw new Error('Value must be unique')
        }
        return value
        }, { name: 'unique', isAsync: true })

        // Usage
        vine.string().use(checkUnique({ table: 'users' }))

    Methods

    • Define a boolean value schema with optional strict mode.

      Parameters

      • Optionaloptions: { strict: boolean }

        Configuration options for boolean validation

      Returns VineBoolean

      A VineBoolean schema instance

      vine.boolean({ strict: true }) // Only accepts true/false
      
    • Define a number value schema with optional strict mode.

      Parameters

      • Optionaloptions: { strict: boolean }

        Configuration options for number validation

      Returns VineNumber

      A VineNumber schema instance

      vine.number().min(0).max(100)
      
    • Define a schema type that validates input matches a specific literal value. Useful for validating exact strings, numbers, or boolean values.

      Type Parameters

      • const Value extends Literal

        The literal value type to validate against

      Parameters

      • value: Value

        The exact value that input must match

      Returns VineLiteral<Value>

      A VineLiteral schema instance

      vine.literal('hello') // Only accepts "hello"
      vine.literal(42) // Only accepts 42
      vine.literal(true) // Only accepts true
    • Define an optional value that can be undefined. Chain the "nullable" method to also allow null values in the output.

      Returns VineOptional<undefined>

      A VineOptional schema instance

      vine.optional() // Accepts undefined
      vine.optional().nullable() // Accepts undefined or null
    • Define an object schema with known properties and their validation schemas. You may call "allowUnknownProperties" to merge unknown properties into the output.

      Type Parameters

      • Properties extends Record<string, SchemaTypes>

        Record of property names to their schema types

      Parameters

      • properties: Properties

        Object defining the schema for each property

      Returns VineObject<
          Properties,
          Id<
              {
                  [K in string
                  | number
                  | symbol]?: {
                      [K in string | number | symbol]: Properties[K][typeof ITYPE]
                  }[K]
              } & {
                  [K in string
                  | number
                  | symbol]: {
                      [K in string | number | symbol]: Properties[K][typeof ITYPE]
                  }[K]
              },
          >,
          Id<
              {
                  [K in string
                  | number
                  | symbol]?: {
                      [K in string | number | symbol]: Properties[K][typeof OTYPE]
                  }[K]
              } & {
                  [K in string
                  | number
                  | symbol]: {
                      [K in string | number | symbol]: Properties[K][typeof OTYPE]
                  }[K]
              },
          >,
          Id<
              {
                  [K in string
                  | number
                  | symbol]?: {
                      [K in string | number | symbol as Join<
                          CamelCasify<Words<(...) & (...)>>,
                          "",
                      >]: Properties[K][typeof COTYPE]
                  }[K]
              } & {
                  [K in string
                  | number
                  | symbol]: {
                      [K in string | number | symbol as Join<
                          CamelCasify<Words<K & string>>,
                          "",
                      >]: Properties[K][typeof COTYPE]
                  }[K]
              },
          >,
      >

      A VineObject schema instance

      vine.object({
      name: vine.string().minLength(2),
      age: vine.number().min(0),
      email: vine.string().email().optional()
      })
    • Define an array schema that validates each element against a given schema. All elements in the array must conform to the same schema type.

      Type Parameters

      • Schema extends SchemaTypes

        The schema type for validating array elements

      Parameters

      • schema: Schema

        The schema to validate each array element against

      Returns VineArray<Schema>

      A VineArray schema instance

      vine.array(vine.string()) // Array of strings
      vine.array(vine.object({ id: vine.number() })) // Array of objects
    • Define a tuple schema with fixed length where each element can have its own validation schema.

      Type Parameters

      • Schema extends SchemaTypes[]

        Array of schema types for each tuple position

      Parameters

      • schemas: [...Schema[]]

        Array of schemas for each tuple element

      Returns VineTuple<
          Schema,
          { [K in string
          | number
          | symbol]: Schema[K<K>][typeof ITYPE] },
          { [K in string | number | symbol]: Schema[K<K>][typeof OTYPE] },
          { [K in string | number | symbol]: Schema[K<K>][typeof COTYPE] },
      >

      A VineTuple schema instance

      vine.tuple([
      vine.string(), // First element must be string
      vine.number(), // Second element must be number
      vine.boolean() // Third element must be boolean
      ])
    • Define a record (dictionary) schema with unknown string keys and values that conform to a specific schema type.

      Type Parameters

      • Schema extends SchemaTypes

        The schema type for validating record values

      Parameters

      • schema: Schema

        The schema to validate each record value against

      Returns VineRecord<Schema>

      A VineRecord schema instance

      vine.record(vine.string()) // { [key: string]: string }
      vine.record(vine.number()) // { [key: string]: number }
    • Define an enum schema that validates input against a predefined set of choices. Supports both array-based enums and TypeScript native enums.

      Type Parameters

      • const Values extends readonly unknown[]

        The enum values type (array or enum-like object)

      Parameters

      • values: Values | ((field: FieldContext) => Values)

        Array of allowed values, function returning values, or TypeScript enum

      Returns VineEnum<Values>

      VineEnum or VineNativeEnum schema instance

      // Array-based enum
      vine.enum(['red', 'green', 'blue'])

      // Dynamic enum with function
      vine.enum((field) => getUserRoles(field.meta.userId))

      // TypeScript enum
      enum Status { ACTIVE = 'active', INACTIVE = 'inactive' }
      vine.enum(Status)
    • Define an enum schema that validates input against a predefined set of choices. Supports both array-based enums and TypeScript native enums.

      Type Parameters

      • Values extends EnumLike

        The enum values type (array or enum-like object)

      Parameters

      • values: Values

        Array of allowed values, function returning values, or TypeScript enum

      Returns VineNativeEnum<Values>

      VineEnum or VineNativeEnum schema instance

      // Array-based enum
      vine.enum(['red', 'green', 'blue'])

      // Dynamic enum with function
      vine.enum((field) => getUserRoles(field.meta.userId))

      // TypeScript enum
      enum Status { ACTIVE = 'active', INACTIVE = 'inactive' }
      vine.enum(Status)
    • Define a schema that accepts any value without validation. Use sparingly as it bypasses type safety and validation.

      Returns VineAny

      A VineAny schema instance

      vine.any() // Accepts any value: string, number, object, etc.
      
    • Define a union of unique schema types with intelligent type discrimination. Unlike regular unions, this validates against the most specific matching schema using runtime type checking.

      Type Parameters

      • Schema extends SchemaTypes

        The schema types in the union

      Parameters

      • schemas: Schema[]

        Array of distinct schema types for the union

      Returns VineUnionOfTypes<Schema>

      A VineUnionOfTypes schema instance

      When schemas are not compatible or duplicated

      vine.unionOfTypes([
      vine.string(),
      vine.number(),
      vine.boolean()
      ])

      // For objects with discriminator fields
      vine.unionOfTypes([
      vine.object({ type: vine.literal('user'), name: vine.string() }),
      vine.object({ type: vine.literal('admin'), permissions: vine.array(vine.string()) })
      ])
    • Pre-compiles a schema into a validation function for better performance when validating multiple data sets against the same schema.

      Type Parameters

      Parameters

      • schema: Schema

        The validation schema to compile

      Returns VineValidator<Schema, Record<string, any> | undefined>

      A compiled validator instance

      const validate = vine.compile(schema)
      await validate({ data })
    • Define a callback to validate the metadata given to the validator at runtime. Useful for passing additional context like user IDs or permissions.

      Type Parameters

      • MetaData extends Record<string, any>

      Parameters

      Returns {
          compile: <Schema extends SchemaTypes>(
              schema: Schema,
          ) => VineValidator<Schema, MetaData>;
      }

      Object with compile method that accepts metadata type

      const validate = vine.withMetaData<{ userId: string }>()
      .compile(schema)
      await validate(data, { meta: { userId: '123' } })
    • Validate data against a schema. Optionally, you can define error messages, fields, a custom messages provider, or an error reporter.

      Type Parameters

      Parameters

      • options: { schema: Schema; data: any } & {
            messagesProvider?: MessagesProviderContact;
            errorReporter?: () => ErrorReporterContract;
        } & { meta?: Record<string, any> }

        Configuration object containing schema, data, and validation options

        • schema: Schema

          Schema to use for validation

        • data: any

          Data to validate

        • OptionalmessagesProvider?: MessagesProviderContact

          Custom messages provider for internationalization and error message customization. If not provided, the default messages provider will be used.

        • OptionalerrorReporter?: () => ErrorReporterContract

          Factory function for creating error reporters. Error reporters control how validation errors are collected and formatted.

        • Optionalmeta?: Record<string, any>

          Optional metadata to pass to validators for additional context

      Returns Promise<Infer<Schema>>

      Promise resolving to validated and typed data

      When validation fails

      await vine.validate({ schema, data })
      await vine.validate({ schema, data, messages, fields })

      await vine.validate({ schema, data, messages, fields }, {
      errorReporter
      })
    • Validate data against a schema without throwing the "ValidationError" exception. Instead the validation errors are returned within the return value.

      Type Parameters

      Parameters

      • options: { schema: Schema; data: any } & {
            messagesProvider?: MessagesProviderContact;
            errorReporter?: () => ErrorReporterContract;
        } & { meta?: Record<string, any> }

        Configuration object containing schema, data, and validation options

        • schema: Schema

          Schema to use for validation

        • data: any

          Data to validate

        • OptionalmessagesProvider?: MessagesProviderContact

          Custom messages provider for internationalization and error message customization. If not provided, the default messages provider will be used.

        • OptionalerrorReporter?: () => ErrorReporterContract

          Factory function for creating error reporters. Error reporters control how validation errors are collected and formatted.

        • Optionalmeta?: Record<string, any>

          Optional metadata to pass to validators for additional context

      Returns Promise<[ValidationError, null] | [null, Infer<Schema>]>

      Promise resolving to tuple of [error, null] or [null, validatedData]

      await vine.tryValidate({ schema, data })
      await vine.tryValidate({ schema, data, messages, fields })

      await vine.tryValidate({ schema, data, messages, fields }, {
      errorReporter
      })