### Install VineJS using npm Source: https://vinejs.dev/docs/getting_started Install the VineJS package using npm. This is the first step to using VineJS in your project. ```bash npm i @vinejs/vine ``` -------------------------------- ### Install VineJS using pnpm Source: https://vinejs.dev/docs/getting_started Install the VineJS package using pnpm. This is another alternative package manager. ```bash pnpm add @vinejs/vine ``` -------------------------------- ### Example: sameAs Source: https://vinejs.dev/docs/types/date Ensures the `exit_date` is the same as the `entry_date`. ```APIDOC ## Example: sameAs ```javascript const schema = vine.object({ entry_date: vine.date(), exit_date: vine.date().sameAs('entry_date') }) ``` ``` -------------------------------- ### Install VineJS using yarn Source: https://vinejs.dev/docs/getting_started Install the VineJS package using yarn. This is an alternative to npm for package management. ```bash yarn add @vinejs/vine ``` -------------------------------- ### startsWith Source: https://vinejs.dev/docs/types/string Ensures the string value starts with a specified substring. ```APIDOC ## startsWith ### Description Ensures the field's value starts with the pre-defined substring. ### Method `startsWith(substring: string)` ### Parameters #### Path Parameters - **substring** (string) - Required - The substring the field's value must start with. ### Request Example ```javascript vine.object({ email: vine .string() .startsWith('+91') }) ``` ``` -------------------------------- ### CreditCardOptions Usage Example Source: https://vinejs.dev/api/types/src_types.CreditCardOptions.html Example of how to use the CreditCardOptions type to specify accepted credit card providers. ```APIDOC const options: CreditCardOptions = { provider: ['visa', 'mastercard', 'amex'] } ``` -------------------------------- ### Example: after Source: https://vinejs.dev/docs/types/date Ensures the input date is after 'today' or a specific date like '2024-01-01'. ```APIDOC ## Example: after ```javascript const schema = vine.object({ checkin_date: vine .date() .after('today') }) const schema = vine.object({ checkin_date: vine .date() .after('2024-01-01') }) ``` ``` -------------------------------- ### startsWith() Source: https://vinejs.dev/api/classes/index.VineString Ensures the value starts with a specified substring. Returns the string schema instance for method chaining. ```APIDOC ## startsWith(substring: string) ### Description Ensures the value starts with a specified substring. ### Parameters #### Path Parameters - **substring** (string) - Required - The required starting substring. ### Returns VineString - This string schema instance for method chaining. ### Example ``` vine.string().startsWith('https://') ``` ``` -------------------------------- ### Example: equals Source: https://vinejs.dev/docs/types/date Ensures the input date is exactly '2024-01-28'. ```APIDOC ## Example: equals ```javascript const schema = vine.object({ enrollment_date: vine .date() .equals('2024-01-28') }) ``` ``` -------------------------------- ### FieldOptions Example Usage Source: https://vinejs.dev/api/types/src_types.FieldOptions.html Demonstrates how to use the FieldOptions type to configure validation behavior for a field. ```APIDOC const options = { allowNull: false, bail: true, isOptional: false, parse: trimParser } ``` -------------------------------- ### startsWith(substring) Source: https://vinejs.dev/api/classes/index.VineString.html Ensures the value starts with a specified substring. Returns the VineString instance for chaining. ```APIDOC ## startsWith(substring) ### Description Ensures the value starts with a specified substring. ### Method `startsWith(substring: string)` ### Parameters #### Path Parameters - **substring** (string) - Required - The required starting substring. ### Returns VineString - This string schema instance for method chaining. ### Example ``` vine.string().startsWith('https://') ``` ``` -------------------------------- ### Example Usage of ValidationRule Source: https://vinejs.dev/api/types/src_types.ValidationRule.html Demonstrates how to create an instance of the ValidationRule type for a custom validator. ```APIDOC #### Example ```ts const minLengthRule: ValidationRule<{ length: number }> = { validator: minLengthValidator, name: 'minLength', isAsync: false, implicit: false } ``` ``` -------------------------------- ### FieldOptions Configuration Example Source: https://vinejs.dev/api/types/src_types.FieldOptions.html Demonstrates how to configure field validation options, including allowing null, enabling bail on error, marking a field as optional, and applying a custom parser. ```typescript const options: FieldOptions = { allowNull: false, bail: true, isOptional: false, parse: trimParser } ``` ```typescript type FieldOptions = { allowNull: boolean; bail: boolean; isOptional: boolean; parse?: Parser; } ``` -------------------------------- ### NormalizeUrlOptions Example Source: https://vinejs.dev/api/types/src_types.NormalizeUrlOptions.html Defines options for normalizing URLs, controlling hash stripping, www prefix removal, and trailing slash removal. ```typescript const options: NormalizeUrlOptions = { stripHash: true, stripWWW: false, removeTrailingSlash: true } ``` -------------------------------- ### Example Usage of PassportOptions Source: https://vinejs.dev/api/types/src_types.PassportOptions.html Illustrates how to define PassportOptions with a list of accepted country codes for validation. ```typescript const options: PassportOptions = { countryCode: ['US', 'GB', 'CA'] } ``` -------------------------------- ### Example: afterField Source: https://vinejs.dev/docs/types/date Ensures the `checkout_date` is after the `checkin_date`. ```APIDOC ## Example: afterField ```javascript const schema = vine.object({ checkin_date: vine.date(), checkout_date: vine.date().afterField('checkin_date') }) ``` ``` -------------------------------- ### Basic VineString Validation Example Source: https://vinejs.dev/api/classes/index.VineString.html Demonstrates how to create a VineString schema with email, minLength, and maxLength validations. Use this to validate string inputs against common patterns and length constraints. ```typescript const schema = vine.string() .email() .minLength(5) .maxLength(100) const result = await vine.validate({ schema, data: 'user@example.com' }) ``` -------------------------------- ### CreditCardOptions Example Source: https://vinejs.dev/api/types/src_types.CreditCardOptions.html Use this type alias to configure the accepted credit card providers for validation. Ensure the provider names match the accepted values. ```typescript const options: CreditCardOptions = { provider: ['visa', 'mastercard', 'amex'] } ``` ```typescript type CreditCardOptions = { provider: ( | "amex" | "dinersclub" | "discover" | "jcb" | "mastercard" | "unionpay" | "visa" )[]; } ``` -------------------------------- ### StringSchema Implementation Example Source: https://vinejs.dev/api/classes/index.MetaModifier.html Illustrates a basic implementation of a StringSchema adhering to the ConstructableSchema interface, defining input, output, and camelCase output types, along with parsing logic. ```typescript class StringSchema implements ConstructableSchema { [ITYPE]: string | undefined [OTYPE]: string [COTYPE]: string [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions) { return { type: 'literal', subtype: 'string' } } clone() { return new StringSchema() } } ``` -------------------------------- ### DateEqualsOptions Example Source: https://vinejs.dev/api/types/src_types.DateEqualsOptions.html Configure the date equals validation to compare only the day and specify the date format for parsing. ```typescript const options: DateEqualsOptions = { compare: 'day', format: 'YYYY-MM-DD' } ``` -------------------------------- ### AlphaOptions Configuration Example Source: https://vinejs.dev/api/types/src_types.AlphaOptions.html Use this configuration to specify which additional characters are allowed when performing an alphabetic validation. Set boolean flags to true for characters you wish to permit. ```typescript const options: AlphaOptions = { allowSpaces: true, allowUnderscores: false, allowDashes: true } ``` -------------------------------- ### Ensure String Starts With Substring Source: https://vinejs.dev/api/classes/index.VineString.html Validates that a string begins with a specified substring. Useful for checking prefixes like URL schemes. ```javascript vine.string().startsWith('https://') ``` -------------------------------- ### Implementing ConstructableLiteralSchema for Numbers Source: https://vinejs.dev/api/interfaces/src_types.ConstructableLiteralSchema.html Example of implementing the ConstructableLiteralSchema interface for a number type. It defines the necessary type markers and the PARSE method to compile the schema into a literal compiler node. ```typescript class NumberSchema implements ConstructableLiteralSchema { [ITYPE]: number | undefined [OTYPE]: number [COTYPE]: number [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions) { return { type: 'literal', subtype: 'number', propertyName, validations: [] } } clone() { return new NumberSchema() } } ``` -------------------------------- ### Custom String Type Implementation Source: https://vinejs.dev/api/classes/index.BaseType.html Example of extending BaseType to create a custom string schema. This demonstrates the basic structure required for a custom type, including the PARSE and clone methods. ```typescript class CustomStringType extends BaseType { [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions) { return { type: 'literal', name: propertyName, ... } } clone() { return new CustomStringType() } } ``` -------------------------------- ### StringSchema Implementation of ConstructableSchema Source: https://vinejs.dev/api/interfaces/src_types.ConstructableSchema.html An example implementation of the ConstructableSchema interface for a string schema. It defines input, output, and camelCase output types, along with parsing and cloning logic. ```typescript class StringSchema implements ConstructableSchema { [ITYPE]: string | undefined [OTYPE]: string [COTYPE]: string [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions) { return { type: 'literal', subtype: 'string' } } clone() { return new StringSchema() } } ``` -------------------------------- ### Define a Union Schema using vine.union (Not Recommended) Source: https://vinejs.dev/docs/types/union This example demonstrates creating a union schema for a `health_check` field using `vine.union`. It requires explicit conditional logic (`vine.union.if` and `vine.union.else`) to determine which schema to apply based on the value's type. ```javascript const healthCheckSchema = vine.union([ vine.union.if( (value) => vine.helpers.string(value), vine.string().url() ), vine.union.else(vine.boolean()) ]) const schema = vine.object({ health_check: healthCheckSchema }) ``` -------------------------------- ### Add Metadata with .meta() Source: https://vinejs.dev/docs/json-schema-generation Use the .meta() method to attach custom JSON Schema keywords like 'description', 'examples', or 'default' to a field. These properties merge directly into the generated schema. ```typescript import vine from '@vinejs/vine' const schema = vine.object({ title: vine.string() .minLength(10) .maxLength(200) .meta({ description: 'The article title displayed to readers', examples: ['Introduction to VineJS', '10 Tips for Better Validation'] }), publishedAt: vine.string().optional().meta({ description: 'ISO 8601 timestamp when the article goes live', format: 'date-time', default: null }) }) ``` -------------------------------- ### Example Compiler Node Source: https://vinejs.dev/api/types/src_types.CompilerNodes.html Illustrates the structure of a literal node within CompilerNodes. This node represents a literal value in the schema, such as a string, number, or boolean. ```typescript const node: CompilerNodes = { type: 'literal', subtype: 'string', propertyName: 'name', validations: [] } ``` -------------------------------- ### Credit Card Validation with Runtime Options Source: https://vinejs.dev/docs/schema_101 Define a schema with a custom validation rule like `creditCard` that accepts runtime options. This example shows how to pass dynamic provider options. ```typescript const purchaseValidator = vine.create({ credit_card: vine.string().creditCard({ provider: [] // SHOULD BE BASED ON USER PROFILE }) }) ``` -------------------------------- ### Validate Object with Conditional Groups Schema Source: https://vinejs.dev/ This example shows how to define a conditional schema using vine.group.if and vine.group.else. The 'guide_id' and 'amount' fields are only required if 'is_hiring_guide' is true. ```javascript import vine from '@vinejs/vine' /** * Conditional schema when hiring or not hiring * a guide */ const guideSchema = vine.group([ vine.group.if( (data) => vine.helpers.isTrue(data.is_hiring_guide), { is_hiring_guide: vine.literal(true), guide_id: vine.string(), amount: vine.number(), } ), vine.group.else({ is_hiring_guide: vine.literal(false), }), ]) const schema = vine .object({ visitor_name: vine.string(), }) .merge(guideSchema) const data = getDataToValidate() await vine.validate({ schema, data }) ``` -------------------------------- ### Vine Constructor Source: https://vinejs.dev/api/classes/index.Vine.html Initializes a new instance of the Vine class. It applies all registered instance properties to the new instance, binding functions to the instance context. ```APIDOC ## constructor * new Vine(): Vine 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 ``` -------------------------------- ### Custom Field Mappings Example Source: https://vinejs.dev/api/variables/src_defaults.fields.html Define custom mappings for nested field paths to create user-friendly error messages. Field paths use dot notation for nested objects. ```javascript const customFields = { 'user.email': 'Email Address', 'user.firstName': 'First Name', 'user.lastName': 'Last Name', 'billing.address': 'Billing Address' } // Field paths use dot notation for nested objects 'user.profile.bio' → 'Biography' 'settings.notifications.email' → 'Email Notifications' ``` -------------------------------- ### Generated JSON Schema Example Source: https://vinejs.dev/docs/json-schema-generation The output of `toJSONSchema()` adheres to the JSON Schema Draft 7 specification. This example shows the schema generated from the basic VineJS object. ```json { "type": "object", "properties": { "name": { "type": "string" }, "email": { "type": "string", "format": "email" }, "age": { "type": "number", "minimum": 18 } }, "required": ["name", "email", "age"], "additionalProperties": false } ``` -------------------------------- ### VineRecord Constructor Source: https://vinejs.dev/api/classes/index.VineRecord.html Creates a new VineRecord instance with a schema for values and optional configuration. ```APIDOC ## constructor new VineRecord(schema: Schema, options?: FieldOptions, validations?: Validation[]): VineRecord ### Description Creates a new VineRecord instance with value schema and optional configuration. ### Parameters * **schema**: Schema - The schema to validate each record value * **options**: FieldOptions - Optional field options like bail mode and nullability * **validations**: Validation[] - Optional initial set of validations to apply ### Returns VineRecord - A new VineRecord instance. ``` -------------------------------- ### VineNativeFile Constructor Source: https://vinejs.dev/api/classes/index.VineNativeFile.html Creates a new VineNativeFile instance with optional field options and initial validations. ```APIDOC ## constructor * new VineNativeFile( options?: Partial, validations?: Validation[], ): VineNativeFile ### Parameters * `Optional`options: Partial Field options like bail mode and nullability * `Optional`validations: Validation[] Initial set of validations to apply ### Returns VineNativeFile ``` -------------------------------- ### Accessing Native File Instance Source: https://vinejs.dev/api/classes/index.VineNativeFile.html Demonstrates how to access a native File instance from an HTML file input event in a browser environment. ```javascript // From HTML file input // const file = event.target.files[0] // This is a native File instance ``` -------------------------------- ### Convert to Lowercase Source: https://vinejs.dev/api/classes/index.VineString.html Converts the string field value to lowercase. For example, 'HELLO' becomes 'hello'. ```typescript vine.string().toLowerCase() // "HELLO" becomes "hello" ``` -------------------------------- ### Constructor Source: https://vinejs.dev/api/classes/index._internal_.MetaModifier.html Initializes a new instance of MetaModifier. ```APIDOC ## constructor * new MetaModifier>(parent: Schema, meta: JSONSchema7): MetaModifier ### Parameters * parent: Schema * meta: JSONSchema7 ### Returns MetaModifier ``` -------------------------------- ### Convert to Uppercase Source: https://vinejs.dev/api/classes/index.VineString.html Converts the string field value to uppercase. For example, 'hello' becomes 'HELLO'. ```typescript vine.string().toUpperCase() // "hello" becomes "HELLO" ``` -------------------------------- ### AlphaNumericOptions Example Source: https://vinejs.dev/api/types/src_types.AlphaNumericOptions.html Use this type to define options for alphanumeric validation, allowing spaces and underscores. ```typescript const options: AlphaNumericOptions = { allowSpaces: true, allowUnderscores: true } ``` -------------------------------- ### Trim Whitespace Source: https://vinejs.dev/api/classes/index.VineString.html Trims leading and trailing whitespace from the string value. For example, ' hello ' becomes 'hello'. ```typescript vine.string().trim() // " hello " becomes "hello" ``` -------------------------------- ### VineAccepted Constructor Source: https://vinejs.dev/api/classes/index.VineAccepted.html Creates a new VineAccepted instance. You can optionally provide initial field options and a set of validations. ```APIDOC ## constructor * new VineAccepted( options?: Partial, validations?: Validation[] ): VineAccepted Creates a new VineAccepted instance. ### Parameters * `Optional`options: Partial Field options like bail mode and nullability * `Optional`validations: Validation[] Initial set of validations to apply ### Returns VineAccepted ``` -------------------------------- ### VineObject Constructor Source: https://vinejs.dev/api/classes/index.VineObject.html Creates a new VineObject instance with property schemas and optional configuration. ```APIDOC ## constructor * new VineObject( properties: Properties, options?: FieldOptions, validations?: Validation[] ): VineObject Creates a new VineObject instance with property schemas and optional configuration. ### Parameters * properties: Properties Record of property names to their validation schemas * `Optional`options: FieldOptions Field options like bail mode and nullability * `Optional`validations: Validation[] Initial set of validations to apply ### Returns VineObject ### Throws Error if properties is not provided ``` -------------------------------- ### Getting Field Path with getFieldPath() Source: https://vinejs.dev/docs/field_context Illustrates how getFieldPath() provides the runtime path for array elements, unlike wildCardPath. ```javascript // Given the following schema const schema = vine.object({ contacts: vine.array( vine.object({ email: vine.string() }) ) }) /** * The return value of "getFieldPath" will be * - "contacts.0.email" * - "contacts.1.email" * - and so on */ /** * The value of "wildCardPath" will be * - "contacts.*.email" */ ``` -------------------------------- ### Checking if Field is Array Member Source: https://vinejs.dev/docs/field_context Provides an example of how to check if a field is part of an array using isArrayMember and access its parent. ```javascript vine.createRule((value, options, field) => { if (field.isArrayMember) { console.log(field.parent[field.name]) } }) ``` -------------------------------- ### Parse Dates with Day.js using Vine Helpers Source: https://vinejs.dev/api/classes/index.Vine.html Demonstrates parsing various date and timestamp formats using the `helpers.asDayJS` function. It supports default formats, Unix timestamps, custom formats, and ISO 8601 strings. ```javascript // 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'] } ``` -------------------------------- ### VineEnum Constructor Source: https://vinejs.dev/api/classes/index.VineEnum.html Creates a new VineEnum instance with the specified allowed values. ```APIDOC ## constructor * new VineEnum( values: Values | ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation[], ): VineEnum Creates a new VineEnum instance with the specified allowed values. #### Type Parameters * const Values extends readonly unknown[] The readonly array of allowed enum values #### Parameters * values: Values | ((field: FieldContext) => Values) Array of allowed values or function returning allowed values * `Optional`options: FieldOptions Field options like bail mode and nullability * `Optional`validations: Validation[] Initial set of validations to apply #### Returns VineEnum ``` -------------------------------- ### Define a MetaDataValidator Source: https://vinejs.dev/api/types/src_types.MetaDataValidator.html Example of defining a MetaDataValidator function. This validator checks if 'userId' exists and is a string within the metadata object. ```typescript const metaValidator: MetaDataValidator = (meta) => { if (!meta.userId || typeof meta.userId !== 'string') { throw new Error('userId is required in metadata') } } ``` -------------------------------- ### VineOptional Constructor Source: https://vinejs.dev/api/classes/index.VineOptional.html Creates a new VineOptional instance. This is used internally by Vine.js but demonstrates how optional schemas are initialized. ```APIDOC ## constructor * new VineOptional( options?: Partial, validations?: Validation[], ): VineOptional Creates a new VineOptional instance. #### Type Parameters * Output The output type when the value is defined #### Parameters * `Optional`options: Partial Field options like bail mode and nullability * `Optional`validations: Validation[] Initial set of validations to apply #### Returns VineOptional ``` -------------------------------- ### Implement Custom Error Reporter Source: https://vinejs.dev/api/interfaces/src_types.ErrorReporterContract.html Example of how to implement the ErrorReporterContract by defining custom logic for reporting and creating validation errors. ```typescript class CustomErrorReporter implements ErrorReporterContract { report(message: string, rule: string, field: FieldContext) { // Custom error reporting logic } createError(): ValidationError { return new ValidationError(this.getErrors()) } } ``` -------------------------------- ### Get Object Properties Source: https://vinejs.dev/api/classes/index.VineObject.html Retrieve a cloned copy of all object properties with their validation schemas. Object groups are excluded for simplicity. ```typescript const properties = schema.getProperties() ``` -------------------------------- ### HTML Form Checkbox Example Source: https://vinejs.dev/api/classes/index.VineAccepted.html When an HTML form checkbox is checked, it typically sends a value like 'on', which is accepted by vine.accepted(). ```html // HTML form checkbox // // When checked, sends "on" which is accepted ``` -------------------------------- ### VineArray Constructor Source: https://vinejs.dev/api/classes/index.VineArray.html Creates a new VineArray instance with element schema and optional configuration. ```APIDOC ## constructor * new VineArray( schema: Schema, options?: FieldOptions, validations?: Validation[], ): VineArray ### Description Creates a new VineArray instance with element schema and optional configuration. ### Parameters * schema: Schema - The schema to validate each array element * `Optional`options: FieldOptions - Field options like bail mode and nullability * `Optional`validations: Validation[] - Initial set of validations to apply ### Returns VineArray ``` -------------------------------- ### Define Native File Schema Source: https://vinejs.dev/docs/types/native_file Use the `nativeFile()` schema type to validate uploaded files. This is the basic setup for accepting any file. ```typescript import vine from '@vinejs/vine' const schema = vine.object({ avatar: vine.nativeFile() }) ``` -------------------------------- ### [PARSE] Source: https://vinejs.dev/api/classes/index._internal_.OptionalModifier.html Compiles to compiler node. ```APIDOC ## [PARSE] ### Description Compiles to compiler node. ### Parameters #### Path Parameters - **propertyName** (string) - Required - The name of the property - **refs** (RefsStore) - Required - The references store - **options** (ParserOptions) - Required - The parser options ### Returns FieldNode & {} & { subtype: string } ``` -------------------------------- ### SimpleError Structure Example Source: https://vinejs.dev/api/types/src_types.SimpleError.html Illustrates the structure of a SimpleError object, which represents a single validation failure. Use this to understand the properties available for each error. ```typescript const error: SimpleError = { message: 'The email field must be a valid email address', field: 'user.email', rule: 'email', meta: { value: 'invalid-email' } } ``` -------------------------------- ### Creating a Union Schema Source: https://vinejs.dev/api/functions/index._internal_.union.html Demonstrates how to create a union schema by providing an array of conditional branches. The first matching condition determines the schema to be used. ```APIDOC ## Function union ### Description Create a new union schema type. A union is a collection of conditionals and schema associated with it. Unions evaluate conditionals in order and apply the first matching schema. Use `union.if()` to define conditional branches and `union.else()` for the default fallback. ### Parameters - `conditionals` (Conditional[]): Array of conditional branches to evaluate ### Returns VineUnion ### Example ```javascript const schema = vine.union([ vine.union.if( (value) => typeof value === 'string', vine.string() ), vine.union.if( (value) => typeof value === 'number', vine.number() ) ]) ``` ``` -------------------------------- ### Validate Date is After Another Field Source: https://vinejs.dev/api/classes/index.VineDate.html Checks if the date is strictly after another field's value. You can customize the comparison unit, for example, to 'minute'. ```typescript vine.date().afterField('startDate') ``` ```typescript vine.date().afterField('createdAt', { compare: 'minute' }) ``` -------------------------------- ### Creating a VineEnum Instance Source: https://vinejs.dev/api/classes/index.VineEnum.html Instantiate VineEnum with an array of allowed values. Optionally, you can provide field options and initial validation rules. ```typescript new VineEnum( values: Values | ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation[], ): VineEnum ``` -------------------------------- ### Implementing IS_OF_TYPE for a String Schema Source: https://vinejs.dev/api/variables/index.symbols.IS_OF_TYPE.html This example shows how to implement the IS_OF_TYPE symbol within a custom schema class. It checks if the provided value is a string. ```typescript class StringSchema { [IS_OF_TYPE](value: unknown) { return typeof value === 'string' } } ``` -------------------------------- ### VineAccepted Methods Source: https://vinejs.dev/api/classes/index.VineAccepted.html Available methods for manipulating and configuring VineAccepted schema instances, including cloning, parsing, and adding validations. ```APIDOC ## Methods ### clone * clone(): this Clones the VineAccepted schema type. The applied options and validations are copied to the new instance. #### Returns this A cloned instance of this VineAccepted schema ### toJSONSchema * toJSONSchema(): JSONSchema7 Transforms your schema type into JSONSchema7 #### Returns JSONSchema7 ### parse * parse(callback: ParseFn): this Define a method to parse the input value. The method is invoked before any validation and hence you must perform type-checking to know the value you are working it. #### Parameters * callback: ParseFn #### Returns this ### use * use(validation: Validation | RuleBuilder): this Adds a validation rule to the schema's validation chain. Rules are executed in the order they are added. #### Parameters * validation: Validation | RuleBuilder The validation rule or rule builder to add #### Returns this This schema instance for method chaining #### Example ``` vine.string().use(minLength({ length: 3 })) vine.number().use(customRule({ strict: true })) Copy ``` ### bail * bail(state: boolean): VineAccepted Enable/disable bail mode for this field. In bail mode, field validations stop after the first error. #### Parameters * state: boolean Whether to enable bail mode #### Returns VineAccepted This schema instance for method chaining #### Example ``` vine.string().bail(false) // Continue validation after first error vine.number().bail(true) // Stop after first error (default) Copy ``` ### optional * optional(): OptionalModifier Mark the field under validation as optional. An optional field allows both null and undefined values. #### Returns OptionalModifier ### nullable * nullable(): NullableModifier Mark the field under validation to be null. The null value will be written to the output as well. If `optional` and `nullable` are used together, then both undefined and null values will be allowed. #### Returns NullableModifier ### meta * meta(meta: Object | JSONSchema7): MetaModifier Add meta to the field that can be retrieved once compiled. It is also merged with the json-schema. #### Parameters * meta: Object | JSONSchema7 #### Returns MetaModifier ``` -------------------------------- ### Define UnionNoMatchCallback Source: https://vinejs.dev/api/types/src_types.UnionNoMatchCallback.html Example of defining a UnionNoMatchCallback function that throws an error when no union variant matches. This callback is invoked with the unmatched input value and the FieldContext. ```typescript const noMatchCallback: UnionNoMatchCallback = (value, field) => { throw new Error(`No union variant matched for field ${field.name}`) } ``` -------------------------------- ### Create VineAccepted Instance Source: https://vinejs.dev/api/classes/index.VineAccepted.html Instantiate VineAccepted with optional field options and validations. Field options include bail mode and nullability. ```typescript new VineAccepted( options?: Partial, validations?: Validation[], ): VineAccepted ``` -------------------------------- ### VineNativeFile Constructor Source: https://vinejs.dev/api/classes/index.VineNativeFile.html Instantiate VineNativeFile with optional field options and an initial set of validations. ```typescript new VineNativeFile( options?: Partial, validations?: Validation[], ): VineNativeFile ``` -------------------------------- ### Define an Uppercase Transformer Source: https://vinejs.dev/api/types/src_types.Transformer.html Create a transformer function that converts a string value to uppercase. This example demonstrates the basic usage of the Transformer type with a StringSchema. ```typescript const uppercaseTransformer: Transformer = (value) => { return value.toUpperCase() } ``` -------------------------------- ### VineString Constructor Source: https://vinejs.dev/api/classes/index.VineString.html Creates a new VineString instance with optional configuration for field options and initial validations. ```APIDOC ## constructor * new VineString( options?: FieldOptions, validations?: Validation[], ): VineString Creates a new VineString instance with optional configuration. ### Parameters * `Optional`options: FieldOptions Field options like bail mode and nullability * `Optional`validations: Validation[] Initial set of validations to apply ### Returns VineString ``` -------------------------------- ### VineDate Constructor Source: https://vinejs.dev/api/classes/index.VineDate.html Creates a new VineDate instance. You can optionally provide configuration options for field settings and initial validations. ```APIDOC ## constructor * new VineDate( options?: Partial & DateFieldOptions, validations?: Validation[], ): VineDate Creates a new VineDate instance with optional configuration. ### Parameters * `Optional`options: Partial & DateFieldOptions Field options including date formats and nullability * `Optional`validations: Validation[] Initial set of validations to apply ### Returns VineDate ``` -------------------------------- ### [PARSE] Source: https://vinejs.dev/api/classes/index.OptionalModifier.html Compiles the schema into compiler nodes for runtime validation. ```APIDOC ## [PARSE] ### Description Compiles to compiler node. ### Method Signature `[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes` ### Parameters #### propertyName - **propertyName** (string) - Required - The name of the property being parsed #### refs - **refs** (RefsStore) - Required - Store for references #### options - **options** (ParserOptions) - Required - Options for the parser ``` -------------------------------- ### Implementing RuleBuilder Interface Source: https://vinejs.dev/api/interfaces/src_types.RuleBuilder.html Example of a custom rule builder class implementing the RuleBuilder interface. This class configures a minimum length validation rule. ```typescript class MinLengthBuilder implements RuleBuilder { constructor(private length: number) {} [VALIDATION](): Validation<{ length: number }> { return { rule: minLengthRule, options: { length: this.length } } } } ``` -------------------------------- ### Applying a Transformation to a String Schema Source: https://vinejs.dev/api/classes/index._internal_.TransformModifier.html Use the `transform` method to apply a function that modifies the validated value. This example converts a validated string to uppercase. ```typescript const schema = vine.string().transform((value) => value.toUpperCase()) // Input: "hello" -> Output: "HELLO" ``` -------------------------------- ### Create a Basic Schema Source: https://vinejs.dev/docs/schema_101 Define the shape of a top-level object using vine.object. Use schema methods like vine.string for field data types. ```javascript const schema = vine.object({ username: vine.string() }) ``` -------------------------------- ### VineCamelCaseObject Utility Methods Source: https://vinejs.dev/api/classes/index._internal_.VineCamelCaseObject.html Provides utility methods for type checking, cloning, and converting the schema to JSON Schema format. ```APIDOC ## Methods ### [IS_OF_TYPE] * "[IS_OF_TYPE]"(value: unknown): boolean ### Description Type checker function to determine if a value is an object. Required for "unionOfTypes" functionality. ### Parameters * **value**: unknown - The value to check. ### Returns boolean - True if the value is a non-null object and not an array. ### clone * clone(): this ### Description Clone object with camelCase conversion preserved. ### Returns this - A cloned instance of this VineCamelCaseObject schema. ### toJSONSchema * toJSONSchema(): JSONSchema7 ### Description Converts the object schema to JSON Schema format. ### Returns JSONSchema7 - JSON Schema representation of this object. ``` -------------------------------- ### Starts With Substring Validation Source: https://vinejs.dev/docs/types/string Ensures a string field begins with a specific substring. Useful for validating phone number prefixes or specific URL schemes. ```javascript vine.object({ email: vine .string() .startsWith('+91') }) ``` -------------------------------- ### Test Custom Rule Failure Source: https://vinejs.dev/docs/extend/custom_rules Test custom validation rules for failure scenarios. This example shows how to assert the number of errors and a specific error message. ```typescript const value = 'foo@example.com' const unique = uniqueRule({ table: 'users', column: 'email' }) const validated = await validator .withContext({ fieldName: 'email' }) .executeAsync(unique, value) validated.assertErrorsCount(1) validated.assertError('The email field is not unique') ``` -------------------------------- ### VineAny Constructor Source: https://vinejs.dev/api/classes/index.VineAny.html Creates a new VineAny instance. You can optionally provide field options and initial validations. ```APIDOC ## constructor * new VineAny( options?: Partial, validations?: Validation[], ): VineAny Creates a new VineAny instance with optional configuration. ### Parameters * `Optional`options: Partial Field options like bail mode and nullability * `Optional`validations: Validation[] Initial set of validations to apply ### Returns VineAny ``` -------------------------------- ### Copy Properties with getProperties Source: https://vinejs.dev/docs/schema_101 Create a new object schema by copying properties from an existing one using object.getProperties. This method clones existing properties into a new object. ```javascript const userSchema = vine.object({ username: vine.string() }) const postSchema = vine.object({ title: vine.string(), author: vine.object({ ...userSchema.getProperties(), id: vine.number(), }) }) ``` -------------------------------- ### Test Custom Rule Success Source: https://vinejs.dev/docs/extend/custom_rules Use the `validator.executeAsync` factory to unit test custom validation rules. This example demonstrates asserting that a validation rule succeeds. ```typescript import { validator } from '@vinejs/vine/factories' import { uniqueRule } from '../src/rules/unique.js' const value = 'foo@bar.com' const unique = uniqueRule({ table: 'users', column: 'email' }) const validated = await validator.executeAsync(unique, value) /** * Assert the validation succeeded. */ validated.assertSucceeded() ``` -------------------------------- ### Validate Object with Array of Objects Schema Source: https://vinejs.dev/docs/introduction This example demonstrates validating an object containing an array of variant objects. Each variant has a name, type (enum), and value. ```typescript import vine from '@vinejs/vine' const schema = vine.object({ sku: vine.string(), price: vine.number().positive(), variants: vine.array( vine.object({ name: vine.string(), type: vine.enum(['size', 'color']), value: vine.string(), }) ) }) const data = getDataToValidate() await vine.validate({ schema, data }) ``` -------------------------------- ### VineString with Custom Validation Rule Source: https://vinejs.dev/api/classes/index.VineNumber.html Illustrates adding a custom validation rule to a VineString schema using the `use` method. The `minLength` rule is used here as an example. ```typescript vine.string().use(minLength({ length: 3 })) ``` -------------------------------- ### SchemaBuilder Constructor Source: https://vinejs.dev/api/classes/index._internal_.SchemaBuilder.html Initializes a new SchemaBuilder instance. This constructor applies all registered instance properties and binds functions to the instance context. ```APIDOC ## constructor * new SchemaBuilder(): SchemaBuilder ### Description 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 SchemaBuilder - A new SchemaBuilder instance. ``` -------------------------------- ### Defining a VineTuple Schema Source: https://vinejs.dev/api/classes/index.VineTuple.html Use vine.tuple to create a schema for a fixed-length array with different types at each position. This example defines a tuple with a string, number, and boolean. ```typescript const schema = vine.tuple([ vine.string(), vine.number(), vine.boolean() ]) const result = await vine.validate({ schema, data: ['hello', 42, true] }) ``` -------------------------------- ### FieldFactory Constructor Source: https://vinejs.dev/api/classes/factories_main.FieldFactory.html Initializes a new instance of the FieldFactory class. ```APIDOC ## Constructor ### constructor * new FieldFactory(): FieldFactory #### Returns FieldFactory ``` -------------------------------- ### Get Compiled Schema and Refs with toJSON Source: https://vinejs.dev/api/classes/index.VineValidator.html Use `toJSON` to retrieve the compiled schema and references. This is useful for caching compiled schemas or debugging validation logic. ```typescript const compiled = validator.toJSON() console.log(compiled.schema) console.log(compiled.refs) ``` -------------------------------- ### VineTuple Constructor Source: https://vinejs.dev/api/classes/index.VineTuple.html Creates a new VineTuple instance with position-specific schemas. You can define schemas for each element, along with optional field options and initial validations. ```APIDOC ## constructor * new VineTuple(schemas: [...Schema[]], options?: FieldOptions, validations?: Validation[]): VineTuple ### Description Creates a new VineTuple instance with position-specific schemas. ### Parameters * schemas: [...Schema[]] - Array of schemas defining validation for each tuple position * `Optional`options: FieldOptions - Field options like bail mode and nullability * `Optional`validations: Validation[] - Initial set of validations to apply ### Returns VineTuple ``` -------------------------------- ### Validate Object with Conditional Groups Schema Source: https://vinejs.dev/docs/introduction This example shows how to define a conditional schema using `vine.group.if` and `vine.group.else`. The schema includes fields that are only required when `is_hiring_guide` is true. ```typescript import vine from '@vinejs/vine' /** * Conditional schema when hiring or not hiring * a guide */ const guideSchema = vine.group([ vine.group.if( (data) => vine.helpers.isTrue(data.is_hiring_guide), { is_hiring_guide: vine.literal(true), guide_id: vine.string(), amount: vine.number(), } ), vine.group.else({ is_hiring_guide: vine.literal(false), }), ]) const schema = vine .object({ visitor_name: vine.string(), }) .merge(guideSchema) const data = getDataToValidate() await vine.validate({ schema, data }) ``` -------------------------------- ### clone() Source: https://vinejs.dev/api/classes/index.VineString.html Clones the VineString schema type, copying applied options and validations to a new instance. ```APIDOC ## clone() ### Description Clones the VineString schema type. The applied options and validations are copied to the new instance. ### Method vine.string().clone() ### Parameters This method does not accept any parameters. ### Request Example ```javascript const originalSchema = vine.string().email() const clonedSchema = originalSchema.clone() ``` ### Response #### Success Response (200) - **this** (object) - A cloned instance of this VineString schema. #### Response Example ```javascript // Example of a successful cloning response (conceptual) // The actual return value is a new VineString schema instance. ``` ``` -------------------------------- ### VineNull Methods Source: https://vinejs.dev/api/classes/index.VineNull.html Provides utility methods for type checking, cloning, and schema conversion. ```APIDOC ## Methods ### [IS_OF_TYPE] * "[IS_OF_TYPE]"(value: unknown): value is null #### Description Type checker function to determine if a value is null. Required for "unionOfTypes" functionality. #### Parameters * value: unknown - The value to check #### Returns * value is null - True if the value is null ### clone * clone(): this #### Description Clones the VineNull schema type. The applied options are copied to the new instance. #### Returns * this - A cloned instance of this VineNull schema ### toJSONSchema * toJSONSchema(): JSONSchema7 #### Description Converts the schema to JSON Schema format. Returns a schema with type 'null'. #### Returns * JSONSchema7 ### [PARSE] * "[PARSE]"( propertyName: string, refs: RefsStore, options: ParserOptions, ): FieldNode & {} & { subtype: string } #### Description Compiles the schema type to a compiler node for validation. #### Parameters * propertyName: string - The name of the property being validated * refs: RefsStore - Reference store for tracking parsers and validators * options: ParserOptions - Parser options including camelCase conversion #### Returns * FieldNode & {} & { subtype: string } ``` -------------------------------- ### Inferring Input Type with InferInput Source: https://vinejs.dev/api/types/src_types.InferInput.html Use InferInput to determine the expected input type for a given schema. This example shows how to infer the type for an optional string schema. ```typescript const schema = vine.string().optional() type Input = InferInput // type Input = string | undefined ``` -------------------------------- ### optional Source: https://vinejs.dev/docs/helpers Clones a raw object and marks all its fields as optional. ```APIDOC ## optional ### Description Clones raw object with vine fields and marks all fields as optional. ### Method Signature vine.helpers.optional(schema: T): T ### Examples ```javascript // Example usage vine.helpers.optional({ name: vine.string(), age: vine.number(), }) // is equivalent to // { // name: vine.string().optional(), // age: vine.number().optional(), // } ``` ``` -------------------------------- ### Integrate VineJS with Ajv for Client-Side Validation Source: https://vinejs.dev/docs/json-schema-generation Generate JSON Schema from a VineJS schema and use it with Ajv for client-side validation. Ensure `ajv-formats` is installed for format support. ```typescript import Ajv from 'ajv' import addFormats from 'ajv-formats' import vine from '@vinejs/vine' /** * Define your VineJS schema. */ const userSchema = vine.object({ email: vine.string().email(), age: vine.number().min(18).max(120) }) /** * Generate JSON Schema from VineJS. */ const validator = vine.create(userSchema) const jsonSchema = validator.toJSONSchema() /** * Set up Ajv with format support for email validation. */ const ajv = new Ajv() addFormats(ajv) /** * Compile the schema for validation. */ const validate = ajv.compile(jsonSchema) /** * Validate data using the generated schema. */ const data = { email: 'user@example.com', age: 25 } const isValid = validate(data) if (!isValid) { console.error('Validation errors:', validate.errors) } ``` -------------------------------- ### FieldFactory.create Source: https://vinejs.dev/api/classes/factories_main.FieldFactory.html Creates a dummy field context with the specified field name and value. Optional providers for messages and error reporting can be supplied. ```APIDOC ## Methods ### create * create( fieldName: string, value: any, messagesProvider?: MessagesProviderContact, errorReporter?: ErrorReporterContract, ): { value: any; isArrayMember: false; parent: any; data: { [key: string]: any }; name: any; wildCardPath: string; getFieldPath(): string; isDefined: boolean; isValid: true; isValidDataType: false; meta: {}; mutate(newValue: any): FieldContext; report( message: string, rule: string, context: FieldContext, args: Record | undefined, ): void; } #### Parameters * fieldName: string * value: any * `Optional`messagesProvider: MessagesProviderContact * `Optional`errorReporter: ErrorReporterContract #### Returns { value: any; isArrayMember: false; parent: any; data: { [key: string]: any }; name: any; wildCardPath: string; getFieldPath(): string; isDefined: boolean; isValid: true; isValidDataType: false; meta: {}; mutate(newValue: any): FieldContext; report( message: string, rule: string, context: FieldContext, args: Record | undefined, ): void; } ``` -------------------------------- ### ConstructableSchema Methods Source: https://vinejs.dev/api/interfaces/src_types.ConstructableSchema.html Details of the methods available on the ConstructableSchema interface. ```APIDOC ## Methods ### [PARSE] * "[PARSE]"( propertyName: string, refs: RefsStore, options: ParserOptions, ): CompilerNodes Compiles the schema into compiler nodes for validation #### Parameters * propertyName: string * refs: RefsStore * options: ParserOptions #### Returns CompilerNodes ### clone * clone(): this Creates a deep copy of the schema instance #### Returns this ### toJSONSchema * toJSONSchema(): JSONSchema7 Transforms your schema type into JSONSchema7 #### Returns JSONSchema7 ``` -------------------------------- ### Define Any Schema Source: https://vinejs.dev/api/classes/index._internal_.SchemaBuilder.html Use vine.any() to create a schema that accepts any value without performing any validation. This should be used cautiously as it bypasses type safety. ```typescript vine.any() // Accepts any value: string, number, object, etc. ``` -------------------------------- ### UndefinedOptional Type Alias Example Source: https://vinejs.dev/api/types/src_types.UndefinedOptional.html Demonstrates how UndefinedOptional makes properties that can be undefined truly optional. Use this type alias to simplify types where explicit undefined values are not required. ```typescript type Before = { name: string; age?: number | undefined } type After = UndefinedOptional // After = { name: string; age?: number } ``` -------------------------------- ### VineBoolean Constructor Source: https://vinejs.dev/api/classes/index.VineBoolean.html Creates a new VineBoolean instance. You can configure options like bail mode, nullability, and strict type checking, and provide initial validation rules. ```APIDOC ## constructor * new VineBoolean( options?: Partial & { strict?: boolean }, validations?: Validation[], ): VineBoolean Creates a new VineBoolean instance with optional configuration. ### Parameters * `Optional`options: Partial & { strict?: boolean } Field options like bail mode, nullability and strict mode * `Optional`validations: Validation[] Initial set of validations to apply ### Returns VineBoolean ```