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.
Define a sub-object as a conditional union group. Groups allow creating conditional validations based on discriminator fields.
Define a union of multiple schema types. Union schemas attempt to validate against each schema until one succeeds.
Messages provider to use on the validator for internationalization and custom error message formatting
Error reporter factory function to use on the validator for formatting validation errors
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
Collection of helper functions to perform type-checking or cast types while keeping HTML forms serialization behavior in mind
Checks if a value exists (is not null and not undefined). Useful for checking if optional form fields have been provided.
The value to check
True if value is not null and not undefined
Checks if a value is missing (null or undefined). The inverse of the exists method.
The value to check
True if value is null or undefined
Checks if a value represents a truthy boolean in HTML form context. Recognizes common HTML form representations of true values.
Accepted truthy values:
The value to check
True if value represents a truthy boolean
Checks if a value represents a falsy boolean in HTML form context. Recognizes common HTML form representations of false values.
Accepted falsy values:
The value to check
True if value represents a falsy boolean
Type guard that checks if a value is a string. Narrows the TypeScript type to string when returning true.
The value to check
True if value is a string, with type narrowing
Type guard that checks if a value is a plain JavaScript object. Excludes null, arrays, and other non-plain objects.
The type of values in the object
The value to check
True if value is a plain object, with type narrowing
Checks if an object contains all the specified keys. Useful for validating object structure before processing.
The object to check
Array of key names that must exist
True if all keys exist in the object
Type guard that checks if a value is an array. Narrows the TypeScript type to array when returning true.
The type of elements in the array
The value to check
True if value is an array, with type narrowing
Checks if a value is numeric (number or string representing a number). Useful for validating form inputs that should contain numeric values.
The value to check
True if value can be converted to a valid number
Converts a value to a number using JavaScript's Number() constructor. Handles null values explicitly by returning NaN.
The value to convert to a number
The numeric representation, or NaN if conversion fails
Converts a value to a boolean using HTML form semantics. Returns null for values that cannot be reliably converted.
Conversion rules:
The value to convert
Boolean value, or null if conversion is ambiguous
Converts a value to a Day.js date object with flexible format support. Handles timestamps, ISO dates, and custom formats with intelligent fallbacks.
The value to convert to a date (string, number, Date, etc.)
Date format(s) to use for parsing. Can be:
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'] }
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.
The input value to compare
The expected value to compare against
Object with comparison result and the casted input value
Validates email addresses using comprehensive rules
Validates URLs with protocol and domain checking
Validates alphabetic characters only
Validates alphanumeric characters only
Validates IP addresses (IPv4 and IPv6)
Validates UUID strings in various formats
Validates ASCII character strings
Validates credit card numbers using Luhn algorithm
Validates International Bank Account Numbers
Validates JSON Web Tokens
Validates latitude/longitude coordinate pairs
Validates mobile phone numbers for various locales
Validates passport numbers for supported countries
Validates postal codes for various countries
Validates URL slugs (lowercase, hyphenated strings)
Validates decimal numbers
Array of supported mobile phone locales/countries
Array of supported postal code country codes
Array of supported passport country codes
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.
The value to validate
True if value is a valid ULID
Validates if a value is a valid hexadecimal color code. Requires the '#' prefix and supports 3, 6, or 8 character hex codes.
Validates if a URL has valid DNS records (A or AAAA records). This performs an actual DNS lookup to verify the domain exists.
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
Retrieves a nested value from the validation context. Supports both dot notation for deep access and direct parent access.
The key or dot-notation path to the value
The field context containing data and parent references
The value at the specified path, or undefined if not found
Utility function to convert a validation function to a Vine schema rule
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.
The type of options the validator accepts
The validation function to convert into a rule
OptionalmetaData: { name?: string; implicit?: boolean; isAsync?: boolean }Optional metadata about the validation rule
Optionalname?: stringCustom name for the validation rule
Optionalimplicit?: booleanWhether the rule should run on null/undefined values
OptionalisAsync?: booleanWhether the validator function is async
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' }))
Define a string value schema with comprehensive validation rules.
A VineString schema instance
Define a boolean value schema with optional strict mode.
Optionaloptions: { strict: boolean }Configuration options for boolean validation
A VineBoolean schema instance
Validate a checkbox or acceptance field to be checked/accepted.
A VineAccepted schema instance
Define a number value schema with optional strict mode.
Optionaloptions: { strict: boolean }Configuration options for number validation
A VineNumber schema instance
Define a datetime value schema with optional parsing options.
Optionaloptions: DateFieldOptionsConfiguration options for date validation
A VineDate schema instance
Define a schema type that validates input matches a specific literal value. Useful for validating exact strings, numbers, or boolean values.
The literal value type to validate against
The exact value that input must match
A VineLiteral schema instance
Define an optional value that can be undefined. Chain the "nullable" method to also allow null values in the output.
A VineOptional schema instance
Define an object schema with known properties and their validation schemas. You may call "allowUnknownProperties" to merge unknown properties into the output.
Record of property names to their schema types
Object defining the schema for each property
A VineObject schema instance
Define an array schema that validates each element against a given schema. All elements in the array must conform to the same schema type.
The schema type for validating array elements
The schema to validate each array element against
A VineArray schema instance
Define a tuple schema with fixed length where each element can have its own validation schema.
Array of schema types for each tuple position
Array of schemas for each tuple element
A VineTuple schema instance
Define a record (dictionary) schema with unknown string keys and values that conform to a specific schema type.
The schema type for validating record values
The schema to validate each record value against
A VineRecord schema instance
Define an enum schema that validates input against a predefined set of choices. Supports both array-based enums and TypeScript native enums.
The enum values type (array or enum-like object)
VineEnum or VineNativeEnum schema instance
Define an enum schema that validates input against a predefined set of choices. Supports both array-based enums and TypeScript native enums.
The enum values type (array or enum-like object)
Array of allowed values, function returning values, or TypeScript enum
VineEnum or VineNativeEnum schema instance
Define a schema that accepts any value without validation. Use sparingly as it bypasses type safety and validation.
A VineAny schema instance
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.
The schema types in the union
Array of distinct schema types for the union
A VineUnionOfTypes schema instance
Define a schema that validates native File instances. Useful for file upload validation in web applications.
A VineNativeFile schema instance
Pre-compiles a schema into a validation function for better performance when validating multiple data sets against the same schema.
The validation schema to compile
A compiled validator instance
Define a callback to validate the metadata given to the validator at runtime. Useful for passing additional context like user IDs or permissions.
Optionalcallback: MetaDataValidatorOptional validator function for metadata
Object with compile method that accepts metadata type
Validate data against a schema. Optionally, you can define error messages, fields, a custom messages provider, or an error reporter.
Configuration object containing schema, data, and validation options
Schema to use for validation
Data to validate
OptionalmessagesProvider?: MessagesProviderContactCustom messages provider for internationalization and error message customization. If not provided, the default messages provider will be used.
OptionalerrorReporter?: () => ErrorReporterContractFactory 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
Promise resolving to validated and typed data
Validate data against a schema without throwing the "ValidationError" exception. Instead the validation errors are returned within the return value.
Configuration object containing schema, data, and validation options
Schema to use for validation
Data to validate
OptionalmessagesProvider?: MessagesProviderContactCustom messages provider for internationalization and error message customization. If not provided, the default messages provider will be used.
OptionalerrorReporter?: () => ErrorReporterContractFactory 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
Promise resolving to tuple of [error, null] or [null, validatedData]
Main Vine class that provides a fluent API for creating validation schemas and validating user input with type-safety using pre-compiled schemas.
Example