prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, {
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
>(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },\n {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(conditon, properties)\n}\n/**", "score": 130.0662004981641 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(() => true, properties)\n}", "score": 117.7255578495554 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 109.80647175685603 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineObject<\n Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n > {\n this.#allowUnknownProperties = true\n return this as VineObject<", "score": 66.65455276219807 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " * reason about.\n */\n getProperties(): Properties {\n return Object.keys(this.#properties).reduce((result, key) => {\n result[key as keyof Properties] = this.#properties[\n key\n ].clone() as Properties[keyof Properties]\n return result\n }, {} as Properties)\n }", "score": 62.29949065012798 } ]
typescript
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [
PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 39.35619249376177 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 34.867738363210634 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 34.546144199958 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " }\n /**\n * Creates a fresh instance of the underlying schema type\n * and wraps it inside the optional modifier\n */\n clone(): this {\n return new OptionalModifier(this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node", "score": 30.951398813233105 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " }\n /**\n * Creates a fresh instance of the underlying schema type\n * and wraps it inside the nullable modifier\n */\n clone(): this {\n return new NullableModifier(this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node", "score": 30.951398813233105 } ]
typescript
PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] ||
!schema[UNIQUE_NAME]) {
throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/builder.ts", "retrieved_chunk": "union.else = function unionElse<Schema extends SchemaTypes>(schema: Schema) {\n return new UnionConditional<Schema>(() => true, schema)\n}", "score": 34.42093574899299 }, { "filename": "src/schema/union/builder.ts", "retrieved_chunk": " */\nunion.if = function unionIf<Schema extends SchemaTypes>(\n conditon: (value: Record<string, unknown>, field: FieldContext) => any,\n schema: Schema\n) {\n return new UnionConditional<Schema>(conditon, schema)\n}\n/**\n * Wrap object properties inside an else conditon\n */", "score": 29.956027300345287 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " clone(): this {\n const cloned = new VineTuple<Schema, Output, CamelCaseOutput>(\n this.#schemas.map((schema) => schema.clone()) as Schema,\n this.cloneOptions(),\n this.cloneValidations()\n )\n if (this.#allowUnknownProperties) {\n cloned.allowUnknownProperties()\n }\n return cloned as this", "score": 29.039399850844152 }, { "filename": "src/vine/main.ts", "retrieved_chunk": " *\n * ```ts\n * const validate = vine.compile(schema)\n * await validate({ data })\n * ```\n */\n compile<Schema extends SchemaTypes>(schema: Schema) {\n return new VineValidator<Schema, Record<string, any> | undefined>(schema, {\n convertEmptyStringsToNull: this.convertEmptyStringsToNull,\n messagesProvider: this.messagesProvider,", "score": 28.32659152353897 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 28.312349724394462 } ]
typescript
!schema[UNIQUE_NAME]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values),
options?: FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 47.82262923560696 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 44.76174282469362 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": "import type { EnumLike, FieldOptions, Validation } from '../../types.js'\n/**\n * VineNativeEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n *\n * The choices list is derived from TypeScript enum data type or an\n * object\n */\nexport class VineNativeEnum<Values extends EnumLike> extends BaseLiteralType<\n Values[keyof Values],", "score": 27.35945778411744 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " super(options, validations || [enumRule({ choices: Object.values(values) })])\n this.#values = values\n }\n /**\n * Clones the VineNativeEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNativeEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }", "score": 20.7638326338573 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 18.329077000580746 } ]
typescript
options?: FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroup } from './group.js' import { OTYPE, COTYPE } from '../../symbols.js' import { CamelCase } from '../camelcase_types.js' import { GroupConditional } from './conditional.js' import type { FieldContext, SchemaTypes } from '../../types.js' /** * Create an object group. Groups are used to conditionally merge properties * to an existing object. */ export function group<Conditional extends GroupConditional<any, any, any>>( conditionals: Conditional[] ) { return new ObjectGroup<Conditional>(conditionals) } /** * Wrap object properties inside a conditonal */ group.if = function groupIf<Properties extends Record<string, SchemaTypes>>( conditon: (value: Record<string, unknown>, field: FieldContext) => any, properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, {
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
>(conditon, properties) } /** * Wrap object properties inside an else conditon */ group.else = function groupElse<Properties extends Record<string, SchemaTypes>>( properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(() => true, properties) }
src/schema/object/group_builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/builder.ts", "retrieved_chunk": " },\n {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(properties)\n }\n /**\n * Define an array field and validate its children elements.\n */\n array<Schema extends SchemaTypes>(schema: Schema) {", "score": 93.57930657217867 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 91.57636406796442 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " * reason about.\n */\n getProperties(): Properties {\n return Object.keys(this.#properties).reduce((result, key) => {\n result[key as keyof Properties] = this.#properties[\n key\n ].clone() as Properties[keyof Properties]\n return result\n }, {} as Properties)\n }", "score": 57.83907039036262 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineObject<\n Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n > {\n this.#allowUnknownProperties = true\n return this as VineObject<", "score": 56.16490355039281 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n >\n }\n /**\n * Merge a union to the object groups. The union can be a \"vine.union\"\n * with objects, or a \"vine.object.union\" with properties.\n */\n merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>(", "score": 49.812911021725256 } ]
typescript
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values
| ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 41.680603865817794 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 34.30050967499362 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 18.329077000580746 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": "import type { EnumLike, FieldOptions, Validation } from '../../types.js'\n/**\n * VineNativeEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n *\n * The choices list is derived from TypeScript enum data type or an\n * object\n */\nexport class VineNativeEnum<Values extends EnumLike> extends BaseLiteralType<\n Values[keyof Values],", "score": 17.99391386756313 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 17.688335997992603 } ]
typescript
| ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { GroupConditional } from './conditional.js' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, UnionNoMatchCallback } from '../../types.js' /** * Object group represents a group with multiple conditionals, where each * condition returns a set of object properties to merge into the * existing object. */ export class ObjectGroup<Conditional extends GroupConditional<any, any, any>> { declare [OTYPE]: Conditional[typeof OTYPE]; declare [COTYPE]: Conditional[typeof COTYPE] #conditionals: Conditional[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionGroup, 'unionGroup', field) } constructor(conditionals: Conditional[]) { this.#conditionals = conditionals } /** * Clones the ObjectGroup schema type. */ clone(): this { const cloned = new ObjectGroup<Conditional>(this.#conditionals) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Define a fallback method to invoke when all of the group conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Compiles the group */
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
return { type: 'group', elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)), } } }
src/schema/object/group.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 55.47267347722571 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 47.4709615368558 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 28.77958232780734 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " this.#otherwiseCallback = callback\n return this\n }\n /**\n * Clones the VineUnion schema type.\n */\n clone(): this {\n const cloned = new VineUnion<Conditional>(this.#conditionals)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this", "score": 23.635410773417718 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 23.566815433084138 } ]
typescript
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values), options?:
FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 41.680603865817794 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 34.30050967499362 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 18.329077000580746 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": "import type { EnumLike, FieldOptions, Validation } from '../../types.js'\n/**\n * VineNativeEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n *\n * The choices list is derived from TypeScript enum data type or an\n * object\n */\nexport class VineNativeEnum<Values extends EnumLike> extends BaseLiteralType<\n Values[keyof Values],", "score": 17.99391386756313 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 17.688335997992603 } ]
typescript
FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { GroupConditional } from './conditional.js' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, UnionNoMatchCallback } from '../../types.js' /** * Object group represents a group with multiple conditionals, where each * condition returns a set of object properties to merge into the * existing object. */ export class ObjectGroup<Conditional extends GroupConditional<any, any, any>> { declare [OTYPE]: Conditional[typeof OTYPE]; declare [COTYPE]: Conditional[typeof COTYPE] #conditionals: Conditional[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionGroup, 'unionGroup', field) } constructor(conditionals: Conditional[]) { this.#conditionals = conditionals } /** * Clones the ObjectGroup schema type. */ clone(): this { const cloned = new ObjectGroup<Conditional>(this.#conditionals) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Define a fallback method to invoke when all of the group conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Compiles the group */ [
PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
return { type: 'group', elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)), } } }
src/schema/object/group.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 29.557393431188736 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 27.313557010746667 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " this.#otherwiseCallback = callback\n return this\n }\n /**\n * Clones the VineUnion schema type.\n */\n clone(): this {\n const cloned = new VineUnion<Conditional>(this.#conditionals)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this", "score": 22.744687494485746 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 22.269150274170734 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 21.746222360482044 } ]
typescript
PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */
export const positiveRule = createRule((value, _, field) => {
/** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * Enforce value to be within the range of minimum and maximum output.\n */\n range(value: [min: number, max: number]) {\n return this.use(rangeRule({ min: value[0], max: value[1] }))\n }\n /**\n * Enforce the value be a positive number\n */\n positive() {", "score": 46.79401468710108 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " static rules = {\n max: maxRule,\n min: minRule,\n range: rangeRule,\n number: numberRule,\n decimal: decimalRule,\n negative: negativeRule,\n positive: positiveRule,\n withoutDecimals: withoutDecimalsRule,\n };", "score": 37.55750818071982 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if ((value as string).length > options.max) {\n field.report(messages.maxLength, 'maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on a string field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 35.69017655572215 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 35.638632593175345 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\n if ((value as unknown[]).length > options.max) {\n field.report(messages['array.maxLength'], 'array.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an array field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 34.449730718777126 } ]
typescript
export const positiveRule = createRule((value, _, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ObjectGroup } from './group.js' import { OTYPE, COTYPE } from '../../symbols.js' import { CamelCase } from '../camelcase_types.js' import { GroupConditional } from './conditional.js' import type { FieldContext, SchemaTypes } from '../../types.js' /** * Create an object group. Groups are used to conditionally merge properties * to an existing object. */ export function group<Conditional extends GroupConditional<any, any, any>>( conditionals: Conditional[] ) { return new ObjectGroup<Conditional>(conditionals) } /** * Wrap object properties inside a conditonal */ group.if = function groupIf<Properties extends Record<string, SchemaTypes>>( conditon: (value: Record<string, unknown>, field: FieldContext) => any, properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof
Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
>(conditon, properties) } /** * Wrap object properties inside an else conditon */ group.else = function groupElse<Properties extends Record<string, SchemaTypes>>( properties: Properties ) { return new GroupConditional< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(() => true, properties) }
src/schema/object/group_builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/builder.ts", "retrieved_chunk": " },\n {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(properties)\n }\n /**\n * Define an array field and validate its children elements.\n */\n array<Schema extends SchemaTypes>(schema: Schema) {", "score": 85.47743558710297 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 80.2688266880606 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineObject<\n Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n > {\n this.#allowUnknownProperties = true\n return this as VineObject<", "score": 49.3002372009874 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " * reason about.\n */\n getProperties(): Properties {\n return Object.keys(this.#properties).reduce((result, key) => {\n result[key as keyof Properties] = this.#properties[\n key\n ].clone() as Properties[keyof Properties]\n return result\n }, {} as Properties)\n }", "score": 46.86590297402769 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " return new VineArray<Schema>(schema)\n }\n /**\n * Define an array field with known length and each children\n * element may have its own schema.\n */\n tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) {\n return new VineTuple<\n Schema,\n { [K in keyof Schema]: Schema[K][typeof OTYPE] },", "score": 45.951432125296954 } ]
typescript
Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Group conditional represents a sub-set of object wrapped * inside a conditional */ export class GroupConditional< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > { declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Properties to merge when conditonal is true */ #properties: Properties /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) { this.#properties = properties this.#conditional = conditional } /** * Compiles to a union conditional */
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {
return { schema: { type: 'sub_object', properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: [], // Compiler allows nested groups, but we are not implementing it }, conditionalFnRefId: refs.trackConditional(this.#conditional), } } }
src/schema/object/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " */\n #schema: Schema\n /**\n * Conditional to evaluate\n */\n #conditional: ConditionalFn<Record<string, unknown>>\n constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema) {\n this.#schema = schema\n this.#conditional = conditional\n }", "score": 72.85567890754106 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " /**\n * Compiles to a union conditional\n */\n [PARSE](\n propertyName: string,\n refs: RefsStore,\n options: ParserOptions\n ): UnionNode['conditions'][number] {\n return {\n conditionalFnRefId: refs.trackConditional(this.#conditional),", "score": 61.63981253224452 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " conditions: this.#conditionals.map((conditional) =>\n conditional[PARSE](propertyName, refs, options)\n ),\n }\n }\n}", "score": 48.62428539291915 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 47.071845433415085 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback\n return this\n }\n /**\n * Compiles the group\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {\n return {\n type: 'group',", "score": 35.27704508695702 } ]
typescript
[PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 39.35619249376177 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 34.867738363210634 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 34.546144199958 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " }\n /**\n * Creates a fresh instance of the underlying schema type\n * and wraps it inside the optional modifier\n */\n clone(): this {\n return new OptionalModifier(this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node", "score": 30.951398813233105 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " }\n /**\n * Creates a fresh instance of the underlying schema type\n * and wraps it inside the nullable modifier\n */\n clone(): this {\n return new NullableModifier(this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node", "score": 30.951398813233105 } ]
typescript
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true
return this.#schema[PARSE](propertyName, refs, options) }
} /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 53.149932435656154 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 53.09213153994968 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 51.75137441887427 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 47.836693688118096 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 45.38813947132059 } ]
typescript
return this.#schema[PARSE](propertyName, refs, options) }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject<
Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> {
/** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 37.162001522860514 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " * The BaseSchema class abstracts the repetitive parts of creating\n * a custom schema type.\n */\nexport abstract class BaseType<Output, CamelCaseOutput> extends BaseModifiersType<\n Output,\n CamelCaseOutput\n> {\n /**\n * Field options\n */", "score": 35.7475870530122 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 33.413379928908235 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 29.18414232350261 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " }\n}\n/**\n * The base type for creating a custom literal type. Literal type\n * is a schema type that has no children elements.\n */\nexport abstract class BaseLiteralType<Output, CamelCaseOutput> extends BaseModifiersType<\n Output,\n CamelCaseOutput\n> {", "score": 27.211237391769586 } ]
typescript
Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) }
constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 59.846527473878005 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 56.40679861482633 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 52.75585928977871 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 50.14314252647717 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 48.83687003956697 } ]
typescript
constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties
: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 59.846527473878005 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 56.40679861482633 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 52.75585928977871 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 50.14314252647717 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 48.83687003956697 } ]
typescript
: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[
typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 48.02846241285064 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 45.06627113444823 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " */\nexport class SchemaBuilder extends Macroable {\n /**\n * Define a sub-object as a union\n */\n group = group\n /**\n * Define a union value\n */\n union = union", "score": 42.06698806358266 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 39.48417211091283 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Represents a union conditional type. A conditional is a predicate\n * with a schema\n */\nexport class UnionConditional<Schema extends SchemaTypes> {\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n /**\n * Properties to merge when conditonal is true", "score": 36.81379102507273 } ]
typescript
typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output
& Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 48.02846241285064 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 45.06627113444823 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " */\nexport class SchemaBuilder extends Macroable {\n /**\n * Define a sub-object as a union\n */\n group = group\n /**\n * Define a union value\n */\n union = union", "score": 42.06698806358266 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 39.48417211091283 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Represents a union conditional type. A conditional is a predicate\n * with a schema\n */\nexport class UnionConditional<Schema extends SchemaTypes> {\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n /**\n * Properties to merge when conditonal is true", "score": 36.81379102507273 } ]
typescript
& Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this
.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " clone(): this {\n const cloned = new VineTuple<Schema, Output, CamelCaseOutput>(\n this.#schemas.map((schema) => schema.clone()) as Schema,\n this.cloneOptions(),\n this.cloneValidations()\n )\n if (this.#allowUnknownProperties) {\n cloned.allowUnknownProperties()\n }\n return cloned as this", "score": 48.10652609795903 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " */\n clone(): this {\n const cloned = new ObjectGroup<Conditional>(this.#conditionals)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this\n }\n /**\n * Define a fallback method to invoke when all of the group conditions\n * fail. You may use this method to report an error.\n */", "score": 30.961240373612828 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return this\n }\n /**\n * Clones the VineUnionOfTypes schema type.\n */\n clone(): this {\n const cloned = new VineUnionOfTypes<Schema>(this.#schemas)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this\n }", "score": 27.8885810195743 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " this.#otherwiseCallback = callback\n return this\n }\n /**\n * Clones the VineUnion schema type.\n */\n clone(): this {\n const cloned = new VineUnion<Conditional>(this.#conditionals)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this", "score": 27.277363029621053 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " clone(): this {\n return new VineString(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 22.083165696774525 } ]
typescript
.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties,
Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 48.02846241285064 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 45.06627113444823 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " */\nexport class SchemaBuilder extends Macroable {\n /**\n * Define a sub-object as a union\n */\n group = group\n /**\n * Define a union value\n */\n union = union", "score": 42.06698806358266 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 39.48417211091283 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Represents a union conditional type. A conditional is a predicate\n * with a schema\n */\nexport class UnionConditional<Schema extends SchemaTypes> {\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n /**\n * Properties to merge when conditonal is true", "score": 36.81379102507273 } ]
typescript
Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.
compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 88.44722780569047 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 82.74503837603847 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 81.31760821915506 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 70.4351166619537 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 68.79084302361782 } ]
typescript
compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, RecordNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' import { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js' /** * VineRecord represents an object of key-value pair in which * keys are unknown */ export class VineRecord<Schema extends SchemaTypes> extends BaseType< { [K: string]: Schema[typeof OTYPE] }, { [K: string]: Schema[typeof COTYPE] } > { /** * Default collection of record rules */ static rules = { maxLength: maxLengthRule, minLength: minLengthRule, fixedLength: fixedLengthRule, validateKeys: validateKeysRule, } #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schema = schema } /** * Enforce a minimum length on an object field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on an object field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on an object field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Register a callback to validate the object keys */ validateKeys
(...args: Parameters<typeof validateKeysRule>) {
return this.use(validateKeysRule(...args)) } /** * Clones the VineRecord schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineRecord( this.#schema.clone(), this.cloneOptions(), this.cloneValidations() ) as this } /** * Compiles to record data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode { return { type: 'record', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, each: this.#schema[PARSE]('*', refs, options), parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/record/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " return this.use(minLengthRule({ min: expectedLength }))\n }\n /**\n * Enforce a maximum length on an array field\n */\n maxLength(expectedLength: number) {\n return this.use(maxLengthRule({ max: expectedLength }))\n }\n /**\n * Enforce a fixed length on an array field", "score": 41.5611320699031 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " }\n /**\n * Enforce a maximum length on a string field\n */\n maxLength(expectedLength: number) {\n return this.use(maxLengthRule({ max: expectedLength }))\n }\n /**\n * Enforce a fixed length on a string field\n */", "score": 38.69182954356473 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Register a callback to validate the object keys\n */\nexport const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>(\n (value, callback, field) => {\n /**\n * Skip if the field is not valid.\n */", "score": 36.69460035705992 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Ensure the array is not empty\n */\n notEmpty() {\n return this.use(notEmptyRule())\n }", "score": 34.580917242139606 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\n if (Object.keys(value as Record<string, any>).length > options.max) {\n field.report(messages['record.maxLength'], 'record.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an object field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 32.7714701891062 } ]
typescript
(...args: Parameters<typeof validateKeysRule>) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */
[UNIQUE_NAME] = 'vine.string';
/** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 32.98079175973228 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " */\n #allowUnknownProperties: boolean = false;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 32.58392753915899 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 31.818907438236668 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 30.73800643387816 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "> extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> {\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'types.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 28.251763111642404 } ]
typescript
[UNIQUE_NAME] = 'vine.string';
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class
VineString extends BaseLiteralType<string, string> {
static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/main.ts", "retrieved_chunk": " withoutDecimalsRule,\n} from './rules.js'\n/**\n * VineNumber represents a numeric value in the validation schema.\n */\nexport class VineNumber extends BaseLiteralType<number, number> {\n protected declare options: FieldOptions & { strict?: boolean }\n /**\n * Default collection of number rules\n */", "score": 27.641717296429718 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": "import { BaseLiteralType } from '../base/literal.js'\nimport { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js'\nimport type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineBoolean represents a boolean value in the validation schema.\n */\nexport class VineBoolean extends BaseLiteralType<boolean, boolean> {\n /**\n * Default collection of boolean rules\n */", "score": 26.62983953311331 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 23.68142151347329 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "}\n/**\n * VineObject represents an object value in the validation\n * schema.\n */\nexport class VineObject<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> extends BaseType<Output, CamelCaseOutput> {", "score": 21.854398116725548 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 19.738920159552436 } ]
typescript
VineString extends BaseLiteralType<string, string> {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>(
(value, locales, field) => {
if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(normalizeEmailRule(options))\n }\n /**\n * Converts the field value to UPPERCASE.\n */\n toUpperCase() {\n return this.use(toUpperCaseRule())\n }\n /**\n * Converts the field value to lowercase.", "score": 34.89277825831214 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Ensure array elements are distinct/unique\n */\nexport const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**", "score": 24.085749167720724 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " if ((value as number) < 0) {\n field.report(messages.positive, 'positive', field)\n }\n})\n/**\n * Enforce the value is a negative number\n */\nexport const negativeRule = createRule<undefined>((value, _, field) => {\n /**\n * Skip if the field is not valid.", "score": 23.148728859139737 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " }\n})\n/**\n * Register a callback to validate the object keys\n */\nexport const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>(\n (value, callback, field) => {\n /**\n * Skip if the field is not valid.\n */", "score": 22.618311933482357 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\n if (Object.keys(value as Record<string, any>).length > options.max) {\n field.report(messages['record.maxLength'], 'record.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an object field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 22.485572659475046 } ]
typescript
(value, locales, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, RecordNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' import { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js' /** * VineRecord represents an object of key-value pair in which * keys are unknown */ export class VineRecord<Schema extends SchemaTypes> extends BaseType< { [K: string]: Schema[typeof OTYPE] }, { [K: string]: Schema[typeof COTYPE] } > { /** * Default collection of record rules */ static rules = { maxLength: maxLengthRule, minLength: minLengthRule, fixedLength: fixedLengthRule, validateKeys: validateKeysRule, } #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schema = schema } /** * Enforce a minimum length on an object field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on an object field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on an object field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Register a callback to validate the object keys */ validateKeys(...args: Parameters<typeof validateKeysRule>) { return this.use(validateKeysRule(...args)) } /** * Clones the VineRecord schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineRecord( this.#schema.clone(), this.cloneOptions(), this.cloneValidations() ) as this } /** * Compiles to record data type */
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {
return { type: 'record', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, each: this.#schema[PARSE]('*', refs, options), parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/record/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 33.61083694524677 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 30.329961776830213 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {\n return {\n type: 'tuple',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,", "score": 29.079811605801048 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 27.742544566797644 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 26.870373605534176 } ]
typescript
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this
.use(urlRule(...args)) }
/** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 27.39946990235522 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if (!helpers.isHexColor(value as string)) {\n field.report(messages.hexCode, 'hexCode', field)\n }\n})\n/**\n * Validates the value to be a valid URL\n */\nexport const urlRule = createRule<URLOptions | undefined>((value, options, field) => {\n if (!field.isValid) {", "score": 26.68404305395138 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " * Enforce a fixed length on an object field\n */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Register a callback to validate the object keys\n */\n validateKeys(...args: Parameters<typeof validateKeysRule>) {\n return this.use(validateKeysRule(...args))", "score": 26.048380981668252 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 25.748119204512783 }, { "filename": "src/schema/any/main.ts", "retrieved_chunk": "/**\n * VineAny represents a value that can be anything\n */\nexport class VineAny extends BaseLiteralType<any, any> {\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super(options, validations)\n }\n /**\n * Clones the VineAny schema type. The applied options\n * and validations are copied to the new instance", "score": 25.513320182201696 } ]
typescript
.use(urlRule(...args)) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find(
(provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/defaults.ts", "retrieved_chunk": " */\nexport const messages = {\n 'required': 'The {{ field }} field must be defined',\n 'string': 'The {{ field }} field must be a string',\n 'email': 'The {{ field }} field must be a valid email address',\n 'mobile': 'The {{ field }} field must be a valid mobile phone number',\n 'creditCard': 'The {{ field }} field must be a valid {{ providersList }} card number',\n 'passport': 'The {{ field }} field must be a valid passport number',\n 'postalCode': 'The {{ field }} field must be a valid postal code',\n 'regex': 'The {{ field }} field format is invalid',", "score": 16.909332776721314 }, { "filename": "src/schema/accepted/rules.ts", "retrieved_chunk": "export const acceptedRule = createRule((value, _, field) => {\n if (!ACCEPTED_VALUES.includes(value as any)) {\n field.report(messages.accepted, 'accepted', field)\n }\n})", "score": 16.79838956045233 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 15.563523171157968 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 15.541701689704407 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " if (helpers.isObject(item) && helpers.hasKeys(item, fieldsList)) {\n const element = fieldsList.map((field) => item[field]).join('_')\n if (uniqueItems.has(element)) {\n return false\n } else {\n uniqueItems.add(element)\n }\n }\n }\n return true", "score": 15.127250108985026 } ]
typescript
(provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) { field.report(messages['record.maxLength'], 'record.maxLength', field, options) } }) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) { field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) } }) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>( (value
, callback, field) => {
/** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " * Enforce a fixed length on an object field\n */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Register a callback to validate the object keys\n */\n validateKeys(...args: Parameters<typeof validateKeysRule>) {\n return this.use(validateKeysRule(...args))", "score": 54.72469711921754 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 37.32519650765162 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 31.6069140115734 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if ((value as string).length > options.max) {\n field.report(messages.maxLength, 'maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on a string field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 30.547226419362982 }, { "filename": "src/defaults.ts", "retrieved_chunk": " 'record': 'The {{ field }} field must be an object',\n 'record.minLength': 'The {{ field }} field must have at least {{ min }} items',\n 'record.maxLength': 'The {{ field }} field must not have more than {{ max }} items',\n 'record.fixedLength': 'The {{ field }} field must contain {{ size }} items',\n 'tuple': 'The {{ field }} field must be an array',\n 'union': 'Invalid value provided for {{ field }} field',\n 'unionGroup': 'Invalid value provided for {{ field }} field',\n 'unionOfTypes': 'Invalid value provided for {{ field }} field',\n}\n/**", "score": 28.902672019219878 } ]
typescript
, callback, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!
helpers.isEmail(value as string, options)) {
field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(activeUrlRule())\n }\n /**\n * Validates the value to be a valid email address\n */\n email(...args: Parameters<typeof emailRule>) {\n return this.use(emailRule(...args))\n }\n /**\n * Validates the value to be a valid mobile number", "score": 34.25256139790913 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 30.986206413135903 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 29.154406592930073 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 29.097230962482136 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 28.96945026508995 } ]
typescript
helpers.isEmail(value as string, options)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, RecordNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' import { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js' /** * VineRecord represents an object of key-value pair in which * keys are unknown */ export class VineRecord<Schema extends SchemaTypes> extends BaseType< { [K: string]: Schema[typeof OTYPE] }, { [K: string]: Schema[typeof COTYPE] } > { /** * Default collection of record rules */ static rules = { maxLength: maxLengthRule, minLength: minLengthRule, fixedLength: fixedLengthRule, validateKeys: validateKeysRule, } #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schema = schema } /** * Enforce a minimum length on an object field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on an object field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on an object field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Register a callback to validate the object keys */ validateKeys(...args: Parameters<typeof validateKeysRule>) { return this.use(validateKeysRule(...args)) } /** * Clones the VineRecord schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineRecord( this.#schema.clone(), this.cloneOptions(), this.cloneValidations() ) as this } /** * Compiles to record data type */ [PARSE](propertyName: string, refs: RefsStore,
options: ParserOptions): RecordNode {
return { type: 'record', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, each: this.#schema[PARSE]('*', refs, options), parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/record/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 31.512077466016198 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {\n return {\n type: 'tuple',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,", "score": 28.847183490672904 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 28.31032931557017 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 27.535536792642187 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 26.654448024393353 } ]
typescript
options: ParserOptions): RecordNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<
RegExp>((value, expression, field) => {
if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 29.08708734552938 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 28.02612604605889 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(regexRule(expression))\n }\n /**\n * Validates the value to contain only letters\n */\n alpha(options?: AlphaOptions) {\n return this.use(alphaRule(options))\n }\n /**\n * Validates the value to contain only letters and", "score": 26.799532720580814 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n mobile(...args: Parameters<typeof mobileRule>) {\n return this.use(mobileRule(...args))\n }\n /**\n * Validates the value to be a valid IP address.\n */\n ipAddress(version?: 4 | 6) {\n return this.use(ipAddressRule(version ? { version } : undefined))\n }", "score": 26.57016685452115 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 26.311696725760832 } ]
typescript
RegExp>((value, expression, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode
const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/types.ts", "retrieved_chunk": " */\nexport type PassportOptions = {\n countryCode: (typeof helpers)['passportCountryCodes'][number][]\n}\n/**\n * Options accepted by the postal code validation\n */\nexport type PostalCodeOptions = {\n countryCode: PostalCodeLocale[]\n}", "score": 41.22171094246856 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 23.479195971327442 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 22.932963564599447 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 21.080124647724062 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Ensure array elements are distinct/unique\n */\nexport const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**", "score": 20.96175547458267 } ]
typescript
const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */
export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => {
if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " if ((value as number) < 0) {\n field.report(messages.positive, 'positive', field)\n }\n})\n/**\n * Enforce the value is a negative number\n */\nexport const negativeRule = createRule<undefined>((value, _, field) => {\n /**\n * Skip if the field is not valid.", "score": 40.90169549941534 }, { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 40.269202870097494 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 39.57891993961461 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 38.48257082177904 }, { "filename": "src/schema/accepted/rules.ts", "retrieved_chunk": "export const acceptedRule = createRule((value, _, field) => {\n if (!ACCEPTED_VALUES.includes(value as any)) {\n field.report(messages.accepted, 'accepted', field)\n }\n})", "score": 38.4422195702565 } ]
typescript
export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */
export class VineString extends BaseLiteralType<string, string> {
static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/main.ts", "retrieved_chunk": " withoutDecimalsRule,\n} from './rules.js'\n/**\n * VineNumber represents a numeric value in the validation schema.\n */\nexport class VineNumber extends BaseLiteralType<number, number> {\n protected declare options: FieldOptions & { strict?: boolean }\n /**\n * Default collection of number rules\n */", "score": 27.641717296429718 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": "import { BaseLiteralType } from '../base/literal.js'\nimport { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js'\nimport type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineBoolean represents a boolean value in the validation schema.\n */\nexport class VineBoolean extends BaseLiteralType<boolean, boolean> {\n /**\n * Default collection of boolean rules\n */", "score": 26.62983953311331 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 23.68142151347329 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": "}\n/**\n * VineObject represents an object value in the validation\n * schema.\n */\nexport class VineObject<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> extends BaseType<Output, CamelCaseOutput> {", "score": 21.854398116725548 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 19.738920159552436 } ]
typescript
export class VineString extends BaseLiteralType<string, string> {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) }
constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 59.083031996423934 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 49.35294756899801 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 47.36991267633732 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 46.93474523454172 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " */\n #allowUnknownProperties: boolean = false;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 43.966229795348326 } ]
typescript
constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {
return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 30.084607923005816 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 30.04180391673991 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " cloned.allowUnknownProperties()\n }\n return cloned as this\n }\n /**\n * Applies camelcase transform\n */\n toCamelCase() {\n return new VineCamelCaseObject(this)\n }", "score": 29.645186314908432 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 25.32150953084436 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " * Clone object\n */\n clone(): this {\n const cloned = new VineObject<Properties, Output, CamelCaseOutput>(\n this.getProperties(),\n this.cloneOptions(),\n this.cloneValidations()\n )\n this.#groups.forEach((group) => cloned.merge(group))\n if (this.#allowUnknownProperties) {", "score": 24.47420395321967 } ]
typescript
[PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor(schemas: [...
Schema], options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 59.083031996423934 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 49.35294756899801 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 47.36991267633732 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 46.93474523454172 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " */\n #allowUnknownProperties: boolean = false;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 43.966229795348326 } ]
typescript
Schema], options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import { RefsStore, TupleNode } from '@vinejs/compiler/types' import { BaseType } from '../base/main.js' import { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js' import type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js' /** * VineTuple is an array with known length and may have different * schema type for each array element. */ export class VineTuple< Schema extends SchemaTypes[], Output extends any[], CamelCaseOutput extends any[], > extends BaseType<Output, CamelCaseOutput> { #schemas: [...Schema] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.array'; /** * Checks if the value is of array type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return Array.isArray(value) } constructor
(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#schemas = schemas } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > { this.#allowUnknownProperties = true return this as unknown as VineTuple< Schema, [...Output, ...Value[]], [...CamelCaseOutput, ...Value[]] > } /** * Clone object */ clone(): this { const cloned = new VineTuple<Schema, Output, CamelCaseOutput>( this.#schemas.map((schema) => schema.clone()) as Schema, this.cloneOptions(), this.cloneValidations() ) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Compiles to array data type */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): TupleNode { return { type: 'tuple', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, allowUnknownProperties: this.#allowUnknownProperties, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)), } } }
src/schema/tuple/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 59.083031996423934 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 49.35294756899801 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 47.36991267633732 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 46.93474523454172 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " */\n #allowUnknownProperties: boolean = false;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 43.966229795348326 } ]
typescript
(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ConditionalFn, RefsStore, UnionNode } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Represents a union conditional type. A conditional is a predicate * with a schema */ export class UnionConditional<Schema extends SchemaTypes> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] /** * Properties to merge when conditonal is true */ #schema: Schema /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema) { this.#schema = schema this.#conditional = conditional } /** * Compiles to a union conditional */
[PARSE]( propertyName: string, refs: RefsStore, options: ParserOptions ): UnionNode['conditions'][number] {
return { conditionalFnRefId: refs.trackConditional(this.#conditional), schema: this.#schema[PARSE](propertyName, refs, options), } } }
src/schema/union/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 46.29783092839615 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " conditions: this.#conditionals.map((conditional) =>\n conditional[PARSE](propertyName, refs, options)\n ),\n }\n }\n}", "score": 38.49886472249952 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 36.16391262858463 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 34.088924768622675 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 33.07917841874638 } ]
typescript
[PARSE]( propertyName: string, refs: RefsStore, options: ParserOptions ): UnionNode['conditions'][number] {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { RefsStore, UnionNode } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { OTYPE, COTYPE, PARSE, IS_OF_TYPE } from '../../symbols.js' import type { SchemaTypes, ParserOptions, ConstructableSchema, UnionNoMatchCallback, } from '../../types.js' /** * Vine union represents a union data type. A union is a collection * of conditionals and each condition has an associated schema */ export class VineUnionOfTypes<Schema extends SchemaTypes> implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] #schemas: Schema[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionOfTypes, 'unionOfTypes', field) } constructor(schemas: Schema[]) { this.#schemas = schemas } /** * Define a fallback method to invoke when all of the union conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Clones the VineUnionOfTypes schema type. */ clone(): this { const cloned = new VineUnionOfTypes<Schema>(this.#schemas) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Compiles to a union */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode { return { type: 'union', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#schemas.map((schema) => { return { conditionalFnRefId: refs.trackConditional((value, field) => {
return schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
}), } } }
src/schema/union_of_types/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 76.75501000268159 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 57.4918511116826 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 57.4918511116826 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " /**\n * Compiles to a union conditional\n */\n [PARSE](\n propertyName: string,\n refs: RefsStore,\n options: ParserOptions\n ): UnionNode['conditions'][number] {\n return {\n conditionalFnRefId: refs.trackConditional(this.#conditional),", "score": 57.014723828158736 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 55.742846231640456 } ]
typescript
return schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { ConditionalFn, RefsStore, UnionNode } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Represents a union conditional type. A conditional is a predicate * with a schema */ export class UnionConditional<Schema extends SchemaTypes> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] /** * Properties to merge when conditonal is true */ #schema: Schema /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema) { this.#schema = schema this.#conditional = conditional } /** * Compiles to a union conditional */ [PARSE]( propertyName: string, refs: RefsStore, options
: ParserOptions ): UnionNode['conditions'][number] {
return { conditionalFnRefId: refs.trackConditional(this.#conditional), schema: this.#schema[PARSE](propertyName, refs, options), } } }
src/schema/union/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#schemas.map((schema) => {", "score": 35.56426568250589 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 33.64219800320796 }, { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": " constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) {\n this.#properties = properties\n this.#conditional = conditional\n }\n /**\n * Compiles to a union conditional\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode['conditions'][number] {\n return {\n schema: {", "score": 32.41184366865508 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " conditions: this.#conditionals.map((conditional) =>\n conditional[PARSE](propertyName, refs, options)\n ),\n }\n }\n}", "score": 24.71180476888883 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " ) as this\n }\n /**\n * Compiles to record data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): RecordNode {\n return {\n type: 'record',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,", "score": 23.01324082530866 } ]
typescript
: ParserOptions ): UnionNode['conditions'][number] {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (
typeof helpers)['passportCountryCodes'][number][] }
/** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " PassportOptions | ((field: FieldContext) => PassportOptions)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const countryCodes =\n typeof options === 'function' ? options(field).countryCode : options.countryCode", "score": 17.35036123672407 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " const matchesAnyCountryCode = countryCodes.find((countryCode) =>\n helpers.isPassportNumber(value as string, countryCode)\n )\n if (!matchesAnyCountryCode) {\n field.report(messages.passport, 'passport', field, { countryCodes })\n }\n})\n/**\n * Validates the value to be a valid postal code\n */", "score": 16.27808907904371 }, { "filename": "src/vine/create_rule.ts", "retrieved_chunk": " * Returns args for the validation function.\n */\ntype GetArgs<T> = undefined extends T ? [options?: T] : [options: T]\n/**\n * Convert a validator function to a rule that you can apply\n * to any schema type using the `schema.use` method.\n */\nexport function createRule<Options = undefined>(\n validator: Validator<Options>,\n metaData?: {", "score": 14.16159141241315 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": ")\n/**\n * Validates the value to be a valid credit card number\n */\nexport const creditCardRule = createRule<\n CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */", "score": 13.11153896792159 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n creditCard(...args: Parameters<typeof creditCardRule>) {\n return this.use(creditCardRule(...args))\n }\n /**\n * Validates the value to be a valid passport number\n */\n passport(...args: Parameters<typeof passportRule>) {\n return this.use(passportRule(...args))\n }", "score": 12.146287351236683 } ]
typescript
typeof helpers)['passportCountryCodes'][number][] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */
[UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 29.853003950266764 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 27.322314886506906 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 27.322314886506906 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 26.571074584523647 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 22.975720640040045 } ]
typescript
[UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = {
countryCode: (typeof helpers)['passportCountryCodes'][number][] }
/** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " PassportOptions | ((field: FieldContext) => PassportOptions)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const countryCodes =\n typeof options === 'function' ? options(field).countryCode : options.countryCode", "score": 17.35036123672407 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " const matchesAnyCountryCode = countryCodes.find((countryCode) =>\n helpers.isPassportNumber(value as string, countryCode)\n )\n if (!matchesAnyCountryCode) {\n field.report(messages.passport, 'passport', field, { countryCodes })\n }\n})\n/**\n * Validates the value to be a valid postal code\n */", "score": 16.27808907904371 }, { "filename": "src/vine/create_rule.ts", "retrieved_chunk": " * Returns args for the validation function.\n */\ntype GetArgs<T> = undefined extends T ? [options?: T] : [options: T]\n/**\n * Convert a validator function to a rule that you can apply\n * to any schema type using the `schema.use` method.\n */\nexport function createRule<Options = undefined>(\n validator: Validator<Options>,\n metaData?: {", "score": 14.16159141241315 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": ")\n/**\n * Validates the value to be a valid credit card number\n */\nexport const creditCardRule = createRule<\n CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined)\n>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */", "score": 13.11153896792159 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n creditCard(...args: Parameters<typeof creditCardRule>) {\n return this.use(creditCardRule(...args))\n }\n /**\n * Validates the value to be a valid passport number\n */\n passport(...args: Parameters<typeof passportRule>) {\n return this.use(passportRule(...args))\n }", "score": 12.146287351236683 } ]
typescript
countryCode: (typeof helpers)['passportCountryCodes'][number][] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(
): ValidationError }
/** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 17.906348252480804 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 15.535918372639602 }, { "filename": "src/errors/validation_error.ts", "retrieved_chunk": " * error messages\n */\nexport class ValidationError extends Error {\n /**\n * Http status code for the validation error\n */\n status: number = 422\n /**\n * Internal code for handling the validation error\n * exception", "score": 15.091058477734272 }, { "filename": "src/vine/main.ts", "retrieved_chunk": " messagesProvider: MessagesProviderContact = new SimpleMessagesProvider(messages, fields)\n /**\n * Error reporter to use on the validator\n */\n errorReporter: () => ErrorReporterContract = () => new SimpleErrorReporter()\n /**\n * Control whether or not to convert empty strings to null\n */\n convertEmptyStringsToNull: boolean = false\n /**", "score": 14.991969260414821 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " }\n}\n/**\n * The base type for creating a custom literal type. Literal type\n * is a schema type that has no children elements.\n */\nexport abstract class BaseLiteralType<Output, CamelCaseOutput> extends BaseModifiersType<\n Output,\n CamelCaseOutput\n> {", "score": 14.377347905629628 } ]
typescript
): ValidationError }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string
[IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n /**\n * The child class must implement the clone method\n */\n abstract clone(): this\n /**\n * The output value of the field. The property points to a type only\n * and not the real value.\n */\n declare [OTYPE]: Output;", "score": 29.853003950266764 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 27.322314886506906 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 27.322314886506906 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 26.571074584523647 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 22.975720640040045 } ]
typescript
[IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */
export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/vine/validator.ts", "retrieved_chunk": " */\nexport class VineValidator<\n Schema extends SchemaTypes,\n MetaData extends undefined | Record<string, any>,\n> {\n /**\n * Reference to static types\n */\n declare [OTYPE]: Schema[typeof OTYPE]\n /**", "score": 33.06893049740198 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " : [options: ValidationOptions<MetaData>]\n ): Promise<Infer<Schema>> {\n if (options?.meta && this.#metaDataValidator) {\n this.#metaDataValidator(options.meta)\n }\n const errorReporter = options?.errorReporter || this.errorReporter\n const messagesProvider = options?.messagesProvider || this.messagesProvider\n return this.#validateFn(\n data,\n options?.meta || {},", "score": 30.26492144304374 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " * meta: { userId: auth.user.id },\n * errorReporter,\n * messagesProvider\n * })\n * ```\n */\n validate(\n data: any,\n ...[options]: [undefined] extends MetaData\n ? [options?: ValidationOptions<MetaData> | undefined]", "score": 28.46082216274322 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": "/**\n * Modifies the schema type to allow null values\n */\nclass NullableModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType<\n Schema[typeof OTYPE] | null,\n Schema[typeof COTYPE] | null\n> {\n #parent: Schema\n constructor(parent: Schema) {\n super()", "score": 25.33206653871714 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " * Modifies the schema type to allow undefined values\n */\nclass OptionalModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType<\n Schema[typeof OTYPE] | undefined,\n Schema[typeof COTYPE] | undefined\n> {\n #parent: Schema\n constructor(parent: Schema) {\n super()\n this.#parent = parent", "score": 24.554651891714297 } ]
typescript
export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder {
[VALIDATION](): Validation<any> }
/** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter { createError(): ValidationError } /** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/symbols.ts", "retrieved_chunk": " * The symbol to generate a validation rule from rule builder\n */\nexport const VALIDATION = Symbol.for('to_validation')", "score": 28.469732429812783 }, { "filename": "src/vine/create_rule.ts", "retrieved_chunk": " implicit?: boolean\n isAsync?: boolean\n }\n) {\n const rule: ValidationRule<Options> = {\n validator,\n isAsync: metaData?.isAsync || validator.constructor.name === 'AsyncFunction',\n implicit: metaData?.implicit ?? false,\n }\n return function (...options: GetArgs<Options>): Validation<Options> {", "score": 25.426870087635443 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n parse(callback: Parser): this {\n this.options.parse = callback\n return this\n }\n /**\n * Push a validation to the validations chain.\n */\n use(validation: Validation<any> | RuleBuilder): this {\n this.validations.push(VALIDATION in validation ? validation[VALIDATION]() : validation)", "score": 23.73461518697743 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " use(validation: Validation<any> | RuleBuilder): this {\n this.validations.push(VALIDATION in validation ? validation[VALIDATION]() : validation)\n return this\n }\n /**\n * Enable/disable the bail mode. In bail mode, the field validations\n * are stopped after the first error.\n */\n bail(state: boolean) {\n this.options.bail = state", "score": 22.11223727794699 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": "import type { LiteralNode, RefsStore } from '@vinejs/compiler/types'\nimport { OTYPE, COTYPE, PARSE, VALIDATION } from '../../symbols.js'\nimport type {\n Parser,\n Validation,\n RuleBuilder,\n Transformer,\n FieldOptions,\n ParserOptions,\n ConstructableSchema,", "score": 20.999888948682553 } ]
typescript
[VALIDATION](): Validation<any> }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { Compiler, refsBuilder } from '@vinejs/compiler' import type { MessagesProviderContact, Refs } from '@vinejs/compiler/types' import { messages } from '../defaults.js' import { OTYPE, PARSE } from '../symbols.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, } from '../types.js' /** * Error messages to share with the compiler */ const COMPILER_ERROR_MESSAGES = { required: messages.required, array: messages.array, object: messages.object, } /** * Vine Validator exposes the API to validate data using a pre-compiled * schema. */ export class VineValidator< Schema extends SchemaTypes, MetaData extends undefined | Record<string, any>, > { /** * Reference to static types */ declare [OTYPE]: Schema[typeof OTYPE] /** * Validator to use to validate metadata */ #metaDataValidator?: MetaDataValidator /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract /** * Parses schema to compiler nodes. */ #parse(schema: Schema) { const refs = refsBuilder() return { compilerNode: { type: 'root' as const,
schema: schema[PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
} /** * Refs computed from the compiled output */ #refs: Refs /** * Compiled validator function */ #validateFn: ReturnType<Compiler['compile']> constructor( schema: Schema, options: { convertEmptyStringsToNull: boolean metaDataValidator?: MetaDataValidator messagesProvider: MessagesProviderContact errorReporter: () => ErrorReporterContract } ) { const { compilerNode, refs } = this.#parse(schema) this.#refs = refs this.#validateFn = new Compiler(compilerNode, { convertEmptyStringsToNull: options.convertEmptyStringsToNull, messages: COMPILER_ERROR_MESSAGES, }).compile() this.errorReporter = options.errorReporter this.messagesProvider = options.messagesProvider this.#metaDataValidator = options.metaDataValidator } /** * Validate data against a schema. Optionally, you can share metaData with * the validator * * ```ts * await validator.validate(data) * await validator.validate(data, { meta: {} }) * * await validator.validate(data, { * meta: { userId: auth.user.id }, * errorReporter, * messagesProvider * }) * ``` */ validate( data: any, ...[options]: [undefined] extends MetaData ? [options?: ValidationOptions<MetaData> | undefined] : [options: ValidationOptions<MetaData>] ): Promise<Infer<Schema>> { if (options?.meta && this.#metaDataValidator) { this.#metaDataValidator(options.meta) } const errorReporter = options?.errorReporter || this.errorReporter const messagesProvider = options?.messagesProvider || this.messagesProvider return this.#validateFn( data, options?.meta || {}, this.#refs, messagesProvider, errorReporter() ) } }
src/vine/validator.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 32.12783416216442 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 30.8710561223458 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 28.748466912503904 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return {\n conditionalFnRefId: refs.trackConditional((value, field) => {\n return schema[IS_OF_TYPE]!(value, field)\n }),\n schema: schema[PARSE](propertyName, refs, options),\n }\n }),\n }\n }\n}", "score": 28.232472593216883 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 28.23055955821951 } ]
typescript
schema: schema[PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ParseFn, RefsStore, TransformFn, FieldContext, CompilerNodes, MessagesProviderContact, ErrorReporterContract as BaseReporter, } from '@vinejs/compiler/types' import type { Options as UrlOptions } from 'normalize-url' import type { IsURLOptions } from 'validator/lib/isURL.js' import type { IsEmailOptions } from 'validator/lib/isEmail.js' import type { NormalizeEmailOptions } from 'validator/lib/normalizeEmail.js' import type { IsMobilePhoneOptions, MobilePhoneLocale } from 'validator/lib/isMobilePhone.js' import type { PostalCodeLocale } from 'validator/lib/isPostalCode.js' import type { helpers } from './vine/helpers.js' import type { ValidationError } from './errors/validation_error.js' import type { OTYPE, COTYPE, PARSE, VALIDATION, UNIQUE_NAME, IS_OF_TYPE } from './symbols.js' /** * Options accepted by the mobile number validation */ export type MobileOptions = { locale?: MobilePhoneLocale[] } & IsMobilePhoneOptions /** * Options accepted by the email address validation */ export type EmailOptions = IsEmailOptions /** * Options accepted by the normalize email */ export { NormalizeEmailOptions } /** * Options accepted by the URL validation */ export type URLOptions = IsURLOptions /** * Options accepted by the credit card validation */ export type CreditCardOptions = { provider: ('amex' | 'dinersclub' | 'discover' | 'jcb' | 'mastercard' | 'unionpay' | 'visa')[] } /** * Options accepted by the passport validation */ export type PassportOptions = { countryCode: (typeof helpers)['passportCountryCodes'][number][] } /** * Options accepted by the postal code validation */ export type PostalCodeOptions = { countryCode: PostalCodeLocale[] } /** * Options accepted by the alpha rule */ export type AlphaOptions = { allowSpaces?: boolean allowUnderscores?: boolean allowDashes?: boolean } export type NormalizeUrlOptions = UrlOptions /** * Options accepted by the alpha numeric rule */ export type AlphaNumericOptions = AlphaOptions /** * Re-exporting selected types from compiler */ export type { Refs, FieldContext, RefIdentifier, ConditionalFn, MessagesProviderContact, } from '@vinejs/compiler/types' /** * Representation of a native enum like type */ export type EnumLike = { [K: string]: string | number; [number: number]: string } /** * Representation of fields and messages accepted by the messages * provider */ export type ValidationMessages = Record<string, string> export type ValidationFields = Record<string, string> /** * Constructable schema type refers to any type that can be * constructed for type inference and compiler output */ export interface ConstructableSchema<Output, CamelCaseOutput> { [OTYPE]: Output [COTYPE]: CamelCaseOutput [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes clone(): this /** * Implement if you want schema type to be used with the unionOfTypes */ [UNIQUE_NAME]?: string [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean } export type SchemaTypes = ConstructableSchema<any, any> /** * Representation of a function that performs validation. * The function receives the following arguments. * * - the current value of the input field * - runtime options * - field context */ export type Validator<Options extends any> = ( value: unknown, options: Options, field: FieldContext ) => any | Promise<any> /** * A validation rule is a combination of a validator and * some metadata required at the time of compiling the * rule. * * Think of this type as "Validator" + "metaData" */ export type ValidationRule<Options extends any> = { validator: Validator<Options> isAsync: boolean implicit: boolean } /** * Validation is a combination of a validation rule and the options * to supply to validator at the time of validating the field. * * Think of this type as "ValidationRule" + "options" */ export type Validation<Options extends any> = { /** * Options to pass to the validator function. */ options?: Options /** * The rule to use */ rule: ValidationRule<Options> } /** * A rule builder is an object that implements the "VALIDATION" * method and returns [[Validation]] type */ export interface RuleBuilder { [VALIDATION](): Validation<any> } /** * The transform function to mutate the output value */ export type Transformer<Schema extends SchemaTypes, Output> = TransformFn< Exclude<Schema[typeof OTYPE], undefined>, Output > /** * The parser function to mutate the input value */ export type Parser = ParseFn /** * A set of options accepted by the field */ export type FieldOptions = { allowNull: boolean bail: boolean isOptional: boolean parse?: Parser } /** * Options accepted when compiling schema types. */ export type ParserOptions = { toCamelCase: boolean } /** * Method to invoke when union has no match */ export type UnionNoMatchCallback<Input> = (value: Input, field: FieldContext) => any /** * Error reporters must implement the reporter contract interface */ export interface ErrorReporterContract extends BaseReporter {
createError(): ValidationError }
/** * The validator function to validate metadata given to a validation * pipeline */ export type MetaDataValidator = (meta: Record<string, any>) => void /** * Options accepted during the validate call. */ export type ValidationOptions<MetaData extends Record<string, any> | undefined> = { /** * Messages provider is used to resolve error messages during * the validation lifecycle */ messagesProvider?: MessagesProviderContact /** * Validation errors are reported directly to an error reporter. The reporter * can decide how to format and output errors. */ errorReporter?: () => ErrorReporterContract } & ([undefined] extends MetaData ? { meta?: MetaData } : { meta: MetaData }) /** * Infers the schema type */ export type Infer<Schema extends { [OTYPE]: any }> = Schema[typeof OTYPE]
src/types.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " field.report(messages.union, 'union', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {", "score": 17.906348252480804 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " }\n constructor(schemas: Schema[]) {\n this.#schemas = schemas\n }\n /**\n * Define a fallback method to invoke when all of the union conditions\n * fail. You may use this method to report an error.\n */\n otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback", "score": 15.535918372639602 }, { "filename": "src/errors/validation_error.ts", "retrieved_chunk": " * error messages\n */\nexport class ValidationError extends Error {\n /**\n * Http status code for the validation error\n */\n status: number = 422\n /**\n * Internal code for handling the validation error\n * exception", "score": 15.091058477734272 }, { "filename": "src/vine/main.ts", "retrieved_chunk": " messagesProvider: MessagesProviderContact = new SimpleMessagesProvider(messages, fields)\n /**\n * Error reporter to use on the validator\n */\n errorReporter: () => ErrorReporterContract = () => new SimpleErrorReporter()\n /**\n * Control whether or not to convert empty strings to null\n */\n convertEmptyStringsToNull: boolean = false\n /**", "score": 14.991969260414821 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " }\n}\n/**\n * The base type for creating a custom literal type. Literal type\n * is a schema type that has no children elements.\n */\nexport abstract class BaseLiteralType<Output, CamelCaseOutput> extends BaseModifiersType<\n Output,\n CamelCaseOutput\n> {", "score": 14.377347905629628 } ]
typescript
createError(): ValidationError }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { Compiler, refsBuilder } from '@vinejs/compiler' import type { MessagesProviderContact, Refs } from '@vinejs/compiler/types' import { messages } from '../defaults.js' import { OTYPE, PARSE } from '../symbols.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, } from '../types.js' /** * Error messages to share with the compiler */ const COMPILER_ERROR_MESSAGES = { required: messages.required, array: messages.array, object: messages.object, } /** * Vine Validator exposes the API to validate data using a pre-compiled * schema. */ export class VineValidator< Schema extends SchemaTypes, MetaData extends undefined | Record<string, any>, > { /** * Reference to static types */ declare [OTYPE]: Schema[typeof OTYPE] /** * Validator to use to validate metadata */ #metaDataValidator?: MetaDataValidator /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract /** * Parses schema to compiler nodes. */ #parse(schema: Schema) { const refs = refsBuilder() return { compilerNode: { type: 'root' as const, schema: schema[
PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
} /** * Refs computed from the compiled output */ #refs: Refs /** * Compiled validator function */ #validateFn: ReturnType<Compiler['compile']> constructor( schema: Schema, options: { convertEmptyStringsToNull: boolean metaDataValidator?: MetaDataValidator messagesProvider: MessagesProviderContact errorReporter: () => ErrorReporterContract } ) { const { compilerNode, refs } = this.#parse(schema) this.#refs = refs this.#validateFn = new Compiler(compilerNode, { convertEmptyStringsToNull: options.convertEmptyStringsToNull, messages: COMPILER_ERROR_MESSAGES, }).compile() this.errorReporter = options.errorReporter this.messagesProvider = options.messagesProvider this.#metaDataValidator = options.metaDataValidator } /** * Validate data against a schema. Optionally, you can share metaData with * the validator * * ```ts * await validator.validate(data) * await validator.validate(data, { meta: {} }) * * await validator.validate(data, { * meta: { userId: auth.user.id }, * errorReporter, * messagesProvider * }) * ``` */ validate( data: any, ...[options]: [undefined] extends MetaData ? [options?: ValidationOptions<MetaData> | undefined] : [options: ValidationOptions<MetaData>] ): Promise<Infer<Schema>> { if (options?.meta && this.#metaDataValidator) { this.#metaDataValidator(options.meta) } const errorReporter = options?.errorReporter || this.errorReporter const messagesProvider = options?.messagesProvider || this.messagesProvider return this.#validateFn( data, options?.meta || {}, this.#refs, messagesProvider, errorReporter() ) } }
src/vine/validator.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 32.12783416216442 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 30.8710561223458 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 28.748466912503904 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return {\n conditionalFnRefId: refs.trackConditional((value, field) => {\n return schema[IS_OF_TYPE]!(value, field)\n }),\n schema: schema[PARSE](propertyName, refs, options),\n }\n }),\n }\n }\n}", "score": 28.232472593216883 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 28.23055955821951 } ]
typescript
PARSE]('', refs, { toCamelCase: false }), }, refs: refs.toJSON(), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from './helpers.js' import { createRule } from './create_rule.js' import { SchemaBuilder } from '../schema/builder.js' import { SimpleMessagesProvider } from '../messages_provider/simple_messages_provider.js' import { VineValidator } from './validator.js' import { fields, messages } from '../defaults.js' import type { Infer, SchemaTypes, MetaDataValidator, ValidationOptions, ErrorReporterContract, MessagesProviderContact, } from '../types.js' import { SimpleErrorReporter } from '../reporters/simple_error_reporter.js' /** * Validate user input with type-safety using a pre-compiled schema. */ export class Vine extends SchemaBuilder { /** * Messages provider to use on the validator */ messagesProvider: MessagesProviderContact = new SimpleMessagesProvider(messages, fields) /** * Error reporter to use on the validator */ errorReporter: () => ErrorReporterContract = () => new SimpleErrorReporter() /** * Control whether or not to convert empty strings to null */ convertEmptyStringsToNull: boolean = false /** * Helpers to perform type-checking or cast types keeping * HTML forms serialization behavior in mind. */ helpers = helpers /** * Convert a validation function to a Vine schema rule */ createRule = createRule /** * Pre-compiles a schema into a validation function. * * ```ts * const validate = vine.compile(schema) * await validate({ data }) * ``` */ compile<Schema extends SchemaTypes>(schema: Schema) {
return new VineValidator<Schema, Record<string, any> | undefined>(schema, {
convertEmptyStringsToNull: this.convertEmptyStringsToNull, messagesProvider: this.messagesProvider, errorReporter: this.errorReporter, }) } /** * Define a callback to validate the metadata given to the validator * at runtime */ withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator) { return { compile: <Schema extends SchemaTypes>(schema: Schema) => { return new VineValidator<Schema, MetaData>(schema, { convertEmptyStringsToNull: this.convertEmptyStringsToNull, messagesProvider: this.messagesProvider, errorReporter: this.errorReporter, metaDataValidator: callback, }) }, } } /** * Validate data against a schema. Optionally, you can define * error messages, fields, a custom messages provider, * or an error reporter. * * ```ts * await vine.validate({ schema, data }) * await vine.validate({ schema, data, messages, fields }) * * await vine.validate({ schema, data, messages, fields }, { * errorReporter * }) * ``` */ validate<Schema extends SchemaTypes>( options: { /** * Schema to use for validation */ schema: Schema /** * Data to validate */ data: any } & ValidationOptions<Record<string, any> | undefined> ): Promise<Infer<Schema>> { const validator = this.compile(options.schema) return validator.validate(options.data, options) } }
src/vine/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/vine/validator.ts", "retrieved_chunk": " }\n /**\n * Validate data against a schema. Optionally, you can share metaData with\n * the validator\n *\n * ```ts\n * await validator.validate(data)\n * await validator.validate(data, { meta: {} })\n *\n * await validator.validate(data, {", "score": 39.97224374294805 }, { "filename": "src/schema/union/builder.ts", "retrieved_chunk": "union.else = function unionElse<Schema extends SchemaTypes>(schema: Schema) {\n return new UnionConditional<Schema>(() => true, schema)\n}", "score": 35.63045657710708 }, { "filename": "src/schema/union/builder.ts", "retrieved_chunk": " */\nunion.if = function unionIf<Schema extends SchemaTypes>(\n conditon: (value: Record<string, unknown>, field: FieldContext) => any,\n schema: Schema\n) {\n return new UnionConditional<Schema>(conditon, schema)\n}\n/**\n * Wrap object properties inside an else conditon\n */", "score": 34.49677898334772 }, { "filename": "src/vine/validator.ts", "retrieved_chunk": " */\nexport class VineValidator<\n Schema extends SchemaTypes,\n MetaData extends undefined | Record<string, any>,\n> {\n /**\n * Reference to static types\n */\n declare [OTYPE]: Schema[typeof OTYPE]\n /**", "score": 31.35717858600223 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " /**\n * Define a union of unique schema types.\n */\n unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) {\n const schemasInUse: Set<string> = new Set()\n schemas.forEach((schema) => {\n if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) {\n throw new Error(\n `Cannot use \"${schema.constructor.name}\". The schema type is not compatible for use with \"vine.unionOfTypes\"`\n )", "score": 29.875518866327578 } ]
typescript
return new VineValidator<Schema, Record<string, any> | undefined>(schema, {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an array field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length < options.min) { field.report(messages['array.minLength'], 'array.minLength', field, options) } }) /** * Enforce a maximum length on an array field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length > options.max) { field.report(messages['array.maxLength'], 'array.maxLength', field, options) } }) /** * Enforce a fixed length on an array field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length !== options.size) { field.report(messages['array.fixedLength'], 'array.fixedLength', field, options) } }) /** * Ensure the array is not empty */ export const notEmptyRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length <= 0) {
field.report(messages.notEmpty, 'notEmpty', field) }
}) /** * Ensure array elements are distinct/unique */ export const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if (!helpers.isDistinct(value as any[], options.fields)) { field.report(messages.distinct, 'distinct', field, options) } }) /** * Removes empty strings, null and undefined values from the array */ export const compactRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } field.mutate( (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''), field ) })
src/schema/array/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 40.08921110996018 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length < options.min) {\n field.report(messages['record.minLength'], 'record.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an object field", "score": 37.69120871924619 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 36.79461591075395 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 28.355538854067667 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 26.044218354754694 } ]
typescript
field.report(messages.notEmpty, 'notEmpty', field) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { RefsStore, UnionNode } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { OTYPE, COTYPE, PARSE, IS_OF_TYPE } from '../../symbols.js' import type { SchemaTypes, ParserOptions, ConstructableSchema, UnionNoMatchCallback, } from '../../types.js' /** * Vine union represents a union data type. A union is a collection * of conditionals and each condition has an associated schema */ export class VineUnionOfTypes<Schema extends SchemaTypes> implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]> { declare [OTYPE]: Schema[typeof OTYPE]; declare [COTYPE]: Schema[typeof COTYPE] #schemas: Schema[] #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => { field.report(messages.unionOfTypes, 'unionOfTypes', field) } constructor(schemas: Schema[]) { this.#schemas = schemas } /** * Define a fallback method to invoke when all of the union conditions * fail. You may use this method to report an error. */ otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this { this.#otherwiseCallback = callback return this } /** * Clones the VineUnionOfTypes schema type. */ clone(): this { const cloned = new VineUnionOfTypes<Schema>(this.#schemas) cloned.otherwise(this.#otherwiseCallback) return cloned as this } /** * Compiles to a union */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode { return { type: 'union', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback), conditions: this.#schemas.map((schema) => { return { conditionalFnRefId: refs.trackConditional((value, field) => { return
schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
}), } } }
src/schema/union_of_types/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 66.85601455875423 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 53.642838279192716 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " /**\n * Compiles to a union conditional\n */\n [PARSE](\n propertyName: string,\n refs: RefsStore,\n options: ParserOptions\n ): UnionNode['conditions'][number] {\n return {\n conditionalFnRefId: refs.trackConditional(this.#conditional),", "score": 53.40444142046467 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " schema: this.#schema[PARSE](propertyName, refs, options),\n }\n }\n}", "score": 48.522200929158494 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 48.20499444017687 } ]
typescript
schema[IS_OF_TYPE]!(value, field) }), schema: schema[PARSE](propertyName, refs, options), }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an array field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length < options.min) { field.report(messages['array.minLength'], 'array.minLength', field, options) } }) /** * Enforce a maximum length on an array field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length > options.max) { field.report(messages['array.maxLength'], 'array.maxLength', field, options) } }) /** * Enforce a fixed length on an array field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length !== options.size) { field.report(messages['array.fixedLength'], 'array.fixedLength', field, options) } }) /** * Ensure the array is not empty */ export const notEmptyRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if ((value as unknown[]).length <= 0) { field.report(messages.notEmpty, 'notEmpty', field) } }) /** * Ensure array elements are distinct/unique */ export const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an array if the field is valid. */ if (!helpers.
isDistinct(value as any[], options.fields)) {
field.report(messages.distinct, 'distinct', field, options) } }) /** * Removes empty strings, null and undefined values from the array */ export const compactRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } field.mutate( (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''), field ) })
src/schema/array/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 49.38226785629323 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 47.3225444163356 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length < options.min) {\n field.report(messages['record.minLength'], 'record.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an object field", "score": 37.219937765313944 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 33.51377073504687 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 33.32097485426975 } ]
typescript
isDistinct(value as any[], options.fields)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { CompilerNodes, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE, VALIDATION } from '../../symbols.js' import type { Parser, Validation, RuleBuilder, FieldOptions, ParserOptions, ConstructableSchema, } from '../../types.js' import Macroable from '@poppinss/macroable' /** * Base schema type with only modifiers applicable on all the schema types. */ export abstract class BaseModifiersType<Output, CamelCaseOutput> extends Macroable implements ConstructableSchema<Output, CamelCaseOutput> { /** * Each subtype should implement the compile method that returns * one of the known compiler nodes */ abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes /** * The child class must implement the clone method */ abstract clone(): this /** * The output value of the field. The property points to a type only * and not the real value. */ declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Mark the field under validation as optional. An optional * field allows both null and undefined values. */ optional(): OptionalModifier<this> { return new OptionalModifier(this) } /** * 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. */ nullable(): NullableModifier<this> { return new NullableModifier(this) } } /** * Modifies the schema type to allow null values */ class NullableModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | null, Schema[typeof COTYPE] | null > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the nullable modifier */ clone(): this { return new NullableModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes { const output
= this.#parent[PARSE](propertyName, refs, options) if (output.type !== 'union') {
output.allowNull = true } return output } } /** * Modifies the schema type to allow undefined values */ class OptionalModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | undefined, Schema[typeof COTYPE] | undefined > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the optional modifier */ clone(): this { return new OptionalModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes { const output = this.#parent[PARSE](propertyName, refs, options) if (output.type !== 'union') { output.isOptional = true } return output } } /** * The BaseSchema class abstracts the repetitive parts of creating * a custom schema type. */ export abstract class BaseType<Output, CamelCaseOutput> extends BaseModifiersType< Output, CamelCaseOutput > { /** * Field options */ protected options: FieldOptions /** * Set of validations to run */ protected validations: Validation<any>[] constructor(options?: FieldOptions, validations?: Validation<any>[]) { super() this.options = options || { bail: true, allowNull: false, isOptional: false, } this.validations = validations || [] } /** * Shallow clones the validations. Since, there are no API's to mutate * the validation options, we can safely copy them by reference. */ protected cloneValidations(): Validation<any>[] { return this.validations.map((validation) => { return { options: validation.options, rule: validation.rule, } }) } /** * Shallow clones the options */ protected cloneOptions(): FieldOptions { return { ...this.options } } /** * Compiles validations */ protected compileValidations(refs: RefsStore) { return this.validations.map((validation) => { return { ruleFnId: refs.track({ validator: validation.rule.validator, options: validation.options, }), implicit: validation.rule.implicit, isAsync: validation.rule.isAsync, } }) } /** * 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. */ parse(callback: Parser): this { this.options.parse = callback return this } /** * Push a validation to the validations chain. */ use(validation: Validation<any> | RuleBuilder): this { this.validations.push(VALIDATION in validation ? validation[VALIDATION]() : validation) return this } /** * Enable/disable the bail mode. In bail mode, the field validations * are stopped after the first error. */ bail(state: boolean) { this.options.bail = state return this } }
src/schema/base/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " clone(): this {\n return new TransformModifier(this.#transform, this.#parent.clone()) as this\n }\n /**\n * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.transformFnId = refs.trackTransformer(this.#transform)\n return output", "score": 72.63167933005447 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " * Compiles to compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.allowNull = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow undefined values", "score": 62.09119841284872 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 53.861702554458525 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n const output = this.#parent[PARSE](propertyName, refs, options)\n output.isOptional = true\n return output\n }\n}\n/**\n * Modifies the schema type to allow custom transformed values\n */\nclass TransformModifier<", "score": 52.764555289418006 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " }\n /**\n * Compiles to a union\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): UnionNode {\n return {\n type: 'union',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),", "score": 44.862461989913044 } ]
typescript
= this.#parent[PARSE](propertyName, refs, options) if (output.type !== 'union') {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import Macroable from '@poppinss/macroable' import type { LiteralNode, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE, VALIDATION } from '../../symbols.js' import type { Parser, Validation, RuleBuilder, Transformer, FieldOptions, ParserOptions, ConstructableSchema, } from '../../types.js' /** * Base schema type with only modifiers applicable on all the schema types. */ abstract class BaseModifiersType<Output, CamelCaseOutput> extends Macroable implements ConstructableSchema<Output, CamelCaseOutput> { /** * Each subtype should implement the compile method that returns * one of the known compiler nodes */ abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode /** * The child class must implement the clone method */ abstract clone(): this /** * The output value of the field. The property points to a type only * and not the real value. */ declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Mark the field under validation as optional. An optional * field allows both null and undefined values. */ optional(): OptionalModifier<this> { return new OptionalModifier(this) } /** * 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. */ nullable(): NullableModifier<this> { return new NullableModifier(this) } /** * Apply transform on the final validated value. The transform method may * convert the value to any new datatype. */ transform<TransformedOutput>( transformer: Transformer<this, TransformedOutput> ): TransformModifier<this, TransformedOutput> { return new TransformModifier(transformer, this) } } /** * Modifies the schema type to allow null values */ class NullableModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | null, Schema[typeof COTYPE] | null > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the nullable modifier */ clone(): this { return new NullableModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { const output =
this.#parent[PARSE](propertyName, refs, options) output.allowNull = true return output }
} /** * Modifies the schema type to allow undefined values */ class OptionalModifier<Schema extends BaseModifiersType<any, any>> extends BaseModifiersType< Schema[typeof OTYPE] | undefined, Schema[typeof COTYPE] | undefined > { #parent: Schema constructor(parent: Schema) { super() this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the optional modifier */ clone(): this { return new OptionalModifier(this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { const output = this.#parent[PARSE](propertyName, refs, options) output.isOptional = true return output } } /** * Modifies the schema type to allow custom transformed values */ class TransformModifier< Schema extends BaseModifiersType<any, any>, Output, > extends BaseModifiersType<Output, Output> { /** * The output value of the field. The property points to a type only * and not the real value. */ declare [OTYPE]: Output; declare [COTYPE]: Output #parent: Schema #transform: Transformer<Schema, Output> constructor(transform: Transformer<Schema, Output>, parent: Schema) { super() this.#transform = transform this.#parent = parent } /** * Creates a fresh instance of the underlying schema type * and wraps it inside the transform modifier. */ clone(): this { return new TransformModifier(this.#transform, this.#parent.clone()) as this } /** * Compiles to compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { const output = this.#parent[PARSE](propertyName, refs, options) output.transformFnId = refs.trackTransformer(this.#transform) return output } } /** * The base type for creating a custom literal type. Literal type * is a schema type that has no children elements. */ export abstract class BaseLiteralType<Output, CamelCaseOutput> extends BaseModifiersType< Output, CamelCaseOutput > { /** * The child class must implement the clone method */ abstract clone(): this /** * Field options */ protected options: FieldOptions /** * Set of validations to run */ protected validations: Validation<any>[] constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) { super() this.options = { bail: true, allowNull: false, isOptional: false, ...options, } this.validations = validations || [] } /** * Shallow clones the validations. Since, there are no API's to mutate * the validation options, we can safely copy them by reference. */ protected cloneValidations(): Validation<any>[] { return this.validations.map((validation) => { return { options: validation.options, rule: validation.rule, } }) } /** * Shallow clones the options */ protected cloneOptions(): FieldOptions { return { ...this.options } } /** * Compiles validations */ protected compileValidations(refs: RefsStore) { return this.validations.map((validation) => { return { ruleFnId: refs.track({ validator: validation.rule.validator, options: validation.options, }), implicit: validation.rule.implicit, isAsync: validation.rule.isAsync, } }) } /** * 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. */ parse(callback: Parser): this { this.options.parse = callback return this } /** * Push a validation to the validations chain. */ use(validation: Validation<any> | RuleBuilder): this { this.validations.push(VALIDATION in validation ? validation[VALIDATION]() : validation) return this } /** * Enable/disable the bail mode. In bail mode, the field validations * are stopped after the first error. */ bail(state: boolean) { this.options.bail = state return this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode { return { type: 'literal', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, validations: this.compileValidations(refs), } } }
src/schema/base/literal.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.allowNull = true\n }\n return output\n }\n}\n/**", "score": 65.92475172268269 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes {\n const output = this.#parent[PARSE](propertyName, refs, options)\n if (output.type !== 'union') {\n output.isOptional = true\n }\n return output\n }\n}\n/**", "score": 61.59582364329226 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n return {\n type: 'object',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 46.684001275778485 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " clone(): this {\n return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this\n }\n /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode {\n options.toCamelCase = true\n return this.#schema[PARSE](propertyName, refs, options)\n }", "score": 43.4528755541421 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 40.004998946384646 } ]
typescript
this.#parent[PARSE](propertyName, refs, options) output.allowNull = true return output }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new
VineLiteral<Value>(value) }
/** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/main.ts", "retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineLiteral represents a type that matches an exact value\n */\nexport class VineLiteral<Value> extends BaseLiteralType<Value, Value> {\n /**\n * Default collection of literal rules\n */\n static rules = {\n equals: equalsRule,", "score": 34.86264891741901 }, { "filename": "src/schema/literal/main.ts", "retrieved_chunk": " }\n #value: Value\n constructor(value: Value, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [equalsRule({ expectedValue: value })])\n this.#value = value\n }\n /**\n * Clones the VineLiteral schema type. The applied options\n * and validations are copied to the new instance\n */", "score": 31.51624400258398 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " */\n isArray<Value>(value: unknown): value is Value[] {\n return Array.isArray(value)\n },\n /**\n * Check if the value is a number or a string representation of a number.\n */\n isNumeric(value: any): boolean {\n return !Number.isNaN(Number(value))\n },", "score": 21.120311874318507 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " }\n /**\n * Clones the VineNumber schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNumber(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 21.04708306751763 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " this.#schemas = schemas\n }\n /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineTuple<\n Schema,\n [...Output, ...Value[]],\n [...CamelCaseOutput, ...Value[]]\n > {", "score": 20.712057692546832 } ]
typescript
VineLiteral<Value>(value) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties
extends Record<string, SchemaTypes>>(properties: Properties) {
return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineObject<\n Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n > {\n this.#allowUnknownProperties = true\n return this as VineObject<", "score": 43.08568799418563 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 41.84194895512299 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " return new ObjectGroup<Conditional>(conditionals)\n}\n/**\n * Wrap object properties inside a conditonal\n */\ngroup.if = function groupIf<Properties extends Record<string, SchemaTypes>>(\n conditon: (value: Record<string, unknown>, field: FieldContext) => any,\n properties: Properties\n) {\n return new GroupConditional<", "score": 40.9209766867468 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n >\n }\n /**\n * Merge a union to the object groups. The union can be a \"vine.union\"\n * with objects, or a \"vine.object.union\" with properties.\n */\n merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>(", "score": 40.801889436187814 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " this.#schemas = schemas\n }\n /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineTuple<\n Schema,\n [...Output, ...Value[]],\n [...CamelCaseOutput, ...Value[]]\n > {", "score": 36.855666193604435 } ]
typescript
extends Record<string, SchemaTypes>>(properties: Properties) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => {
if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) {
throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/builder.ts", "retrieved_chunk": "union.else = function unionElse<Schema extends SchemaTypes>(schema: Schema) {\n return new UnionConditional<Schema>(() => true, schema)\n}", "score": 34.42093574899299 }, { "filename": "src/schema/union/builder.ts", "retrieved_chunk": " */\nunion.if = function unionIf<Schema extends SchemaTypes>(\n conditon: (value: Record<string, unknown>, field: FieldContext) => any,\n schema: Schema\n) {\n return new UnionConditional<Schema>(conditon, schema)\n}\n/**\n * Wrap object properties inside an else conditon\n */", "score": 31.423321303425933 }, { "filename": "src/vine/main.ts", "retrieved_chunk": " *\n * ```ts\n * const validate = vine.compile(schema)\n * await validate({ data })\n * ```\n */\n compile<Schema extends SchemaTypes>(schema: Schema) {\n return new VineValidator<Schema, Record<string, any> | undefined>(schema, {\n convertEmptyStringsToNull: this.convertEmptyStringsToNull,\n messagesProvider: this.messagesProvider,", "score": 29.793885526619615 }, { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " clone(): this {\n const cloned = new VineTuple<Schema, Output, CamelCaseOutput>(\n this.#schemas.map((schema) => schema.clone()) as Schema,\n this.cloneOptions(),\n this.cloneValidations()\n )\n if (this.#allowUnknownProperties) {\n cloned.allowUnknownProperties()\n }\n return cloned as this", "score": 29.039399850844152 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 28.312349724394462 } ]
typescript
if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof
Properties]: Properties[K][typeof OTYPE] }, {
[K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] } >(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 74.75355579776613 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },\n {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(conditon, properties)\n}\n/**", "score": 72.38957184820735 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(() => true, properties)\n}", "score": 63.680624935420596 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " return new ObjectGroup<Conditional>(conditionals)\n}\n/**\n * Wrap object properties inside a conditonal\n */\ngroup.if = function groupIf<Properties extends Record<string, SchemaTypes>>(\n conditon: (value: Record<string, unknown>, field: FieldContext) => any,\n properties: Properties\n) {\n return new GroupConditional<", "score": 47.102008090442226 }, { "filename": "src/schema/object/main.ts", "retrieved_chunk": " /**\n * Copy unknown properties to the final output.\n */\n allowUnknownProperties<Value>(): VineObject<\n Properties,\n Output & { [K: string]: Value },\n CamelCaseOutput & { [K: string]: Value }\n > {\n this.#allowUnknownProperties = true\n return this as VineObject<", "score": 46.24170292749957 } ]
typescript
Properties]: Properties[K][typeof OTYPE] }, {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]
: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] }
>(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },\n {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(conditon, properties)\n}\n/**", "score": 65.50093669340755 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(() => true, properties)\n}", "score": 57.73461447436175 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 57.237780861344554 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 56.50921325533567 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 52.2371623063678 } ]
typescript
: Schema[K][typeof OTYPE] }, { [K in keyof Schema]: Schema[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values), options
?: FieldOptions, validations?: Validation<any>[] ) {
super(options, validations || [enumRule({ choices: values })]) this.#values = values } /** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 41.680603865817794 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 34.30050967499362 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 18.329077000580746 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": "import type { EnumLike, FieldOptions, Validation } from '../../types.js'\n/**\n * VineNativeEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n *\n * The choices list is derived from TypeScript enum data type or an\n * object\n */\nexport class VineNativeEnum<Values extends EnumLike> extends BaseLiteralType<\n Values[keyof Values],", "score": 17.99391386756313 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 17.688335997992603 } ]
typescript
?: FieldOptions, validations?: Validation<any>[] ) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import Macroable from '@poppinss/macroable' import { VineAny } from './any/main.js' import { VineEnum } from './enum/main.js' import { union } from './union/builder.js' import { VineTuple } from './tuple/main.js' import { VineArray } from './array/main.js' import { VineObject } from './object/main.js' import { VineRecord } from './record/main.js' import { VineString } from './string/main.js' import { VineNumber } from './number/main.js' import { VineBoolean } from './boolean/main.js' import { VineLiteral } from './literal/main.js' import { CamelCase } from './camelcase_types.js' import { VineAccepted } from './accepted/main.js' import { group } from './object/group_builder.js' import { VineNativeEnum } from './enum/native_enum.js' import { VineUnionOfTypes } from './union_of_types/main.js' import { OTYPE, COTYPE, IS_OF_TYPE, UNIQUE_NAME } from '../symbols.js' import type { EnumLike, FieldContext, SchemaTypes } from '../types.js' /** * Schema builder exposes methods to construct a Vine schema. You may * add custom methods to it using macros. */ export class SchemaBuilder extends Macroable { /** * Define a sub-object as a union */ group = group /** * Define a union value */ union = union /** * Define a string value */ string() { return new VineString() } /** * Define a boolean value */ boolean(options?: { strict: boolean }) { return new VineBoolean(options) } /** * Validate a checkbox to be checked */ accepted() { return new VineAccepted() } /** * Define a number value */ number(options?: { strict: boolean }) { return new VineNumber(options) } /** * Define a schema type in which the input value * matches the pre-defined value */ literal<const Value>(value: Value) { return new VineLiteral<Value>(value) } /** * Define an object with known properties. You may call "allowUnknownProperties" * to merge unknown properties. */ object<Properties extends Record<string, SchemaTypes>>(properties: Properties) { return new VineObject< Properties, { [K in keyof Properties]: Properties[K][typeof OTYPE] }, { [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE] } >(properties) } /** * Define an array field and validate its children elements. */ array<Schema extends SchemaTypes>(schema: Schema) { return new VineArray<Schema>(schema) } /** * Define an array field with known length and each children * element may have its own schema. */ tuple<Schema extends SchemaTypes[]>(schemas: [...Schema]) { return new VineTuple< Schema, { [K in keyof Schema]: Schema[K][typeof OTYPE] },
{ [K in keyof Schema]: Schema[K][typeof COTYPE] }
>(schemas) } /** * Define an object field with key-value pair. The keys in * a record are unknown and values can be of a specific * schema type. */ record<Schema extends SchemaTypes>(schema: Schema) { return new VineRecord<Schema>(schema) } /** * Define a field whose value matches the enum choices. */ enum<const Values extends readonly unknown[]>( values: Values | ((field: FieldContext) => Values) ): VineEnum<Values> enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values> enum<Values extends readonly unknown[] | EnumLike>(values: Values): any { if (Array.isArray(values) || typeof values === 'function') { return new VineEnum(values) } return new VineNativeEnum(values as EnumLike) } /** * Allow the field value to be anything */ any() { return new VineAny() } /** * Define a union of unique schema types. */ unionOfTypes<Schema extends SchemaTypes>(schemas: Schema[]) { const schemasInUse: Set<string> = new Set() schemas.forEach((schema) => { if (!schema[IS_OF_TYPE] || !schema[UNIQUE_NAME]) { throw new Error( `Cannot use "${schema.constructor.name}". The schema type is not compatible for use with "vine.unionOfTypes"` ) } if (schemasInUse.has(schema[UNIQUE_NAME])) { throw new Error( `Cannot use duplicate schema "${schema[UNIQUE_NAME]}". "vine.unionOfTypes" needs distinct schema types only` ) } schemasInUse.add(schema[UNIQUE_NAME]) }) schemasInUse.clear() return new VineUnionOfTypes(schemas) } }
src/schema/builder.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },\n {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(conditon, properties)\n}\n/**", "score": 65.50093669340755 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " {\n [K in keyof Properties as CamelCase<K & string>]: Properties[K][typeof COTYPE]\n }\n >(() => true, properties)\n}", "score": 57.73461447436175 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " * of conditionals and each condition has an associated schema\n */\nexport class VineUnionOfTypes<Schema extends SchemaTypes>\n implements ConstructableSchema<Schema[typeof OTYPE], Schema[typeof COTYPE]>\n{\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n #schemas: Schema[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionOfTypes, 'unionOfTypes', field)", "score": 57.237780861344554 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": "} from './rules.js'\n/**\n * VineArray represents an array schema type in the validation\n * pipeline\n */\nexport class VineArray<Schema extends SchemaTypes> extends BaseType<\n Schema[typeof OTYPE][],\n Schema[typeof COTYPE][]\n> {\n /**", "score": 56.50921325533567 }, { "filename": "src/schema/object/group_builder.ts", "retrieved_chunk": " * Wrap object properties inside an else conditon\n */\ngroup.else = function groupElse<Properties extends Record<string, SchemaTypes>>(\n properties: Properties\n) {\n return new GroupConditional<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]\n },", "score": 52.2371623063678 } ]
typescript
{ [K in keyof Schema]: Schema[K][typeof COTYPE] }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) {
field.report(messages.min, 'min', field, options) }
}) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 59.862087485789786 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 47.212394421581386 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an array field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 47.212394421581386 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 37.976454399367476 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 37.976454399367476 } ]
typescript
field.report(messages.min, 'min', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report
(messages.max, 'max', field, options) }
}) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 38.65928023181128 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 38.65928023181128 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "})\n/**\n * Enforce a maximum length on a string field\n */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 37.359668035062484 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 33.07248644467101 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 32.48337690951662 } ]
typescript
(messages.max, 'max', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import type { ConditionalFn, ObjectGroupNode, RefsStore } from '@vinejs/compiler/types' import { OTYPE, COTYPE, PARSE } from '../../symbols.js' import type { ParserOptions, SchemaTypes } from '../../types.js' /** * Group conditional represents a sub-set of object wrapped * inside a conditional */ export class GroupConditional< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > { declare [OTYPE]: Output; declare [COTYPE]: CamelCaseOutput /** * Properties to merge when conditonal is true */ #properties: Properties /** * Conditional to evaluate */ #conditional: ConditionalFn<Record<string, unknown>> constructor(conditional: ConditionalFn<Record<string, unknown>>, properties: Properties) { this.#properties = properties this.#conditional = conditional } /** * Compiles to a union conditional */ [PARSE](refs: RefsStore, options:
ParserOptions): ObjectGroupNode['conditions'][number] {
return { schema: { type: 'sub_object', properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: [], // Compiler allows nested groups, but we are not implementing it }, conditionalFnRefId: refs.trackConditional(this.#conditional), } } }
src/schema/object/conditional.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " */\n #schema: Schema\n /**\n * Conditional to evaluate\n */\n #conditional: ConditionalFn<Record<string, unknown>>\n constructor(conditional: ConditionalFn<Record<string, unknown>>, schema: Schema) {\n this.#schema = schema\n this.#conditional = conditional\n }", "score": 72.85567890754106 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": " /**\n * Compiles to a union conditional\n */\n [PARSE](\n propertyName: string,\n refs: RefsStore,\n options: ParserOptions\n ): UnionNode['conditions'][number] {\n return {\n conditionalFnRefId: refs.trackConditional(this.#conditional),", "score": 61.63981253224452 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " conditions: this.#conditionals.map((conditional) =>\n conditional[PARSE](propertyName, refs, options)\n ),\n }\n }\n}", "score": 48.62428539291915 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " elseConditionalFnRefId: refs.trackConditional(this.#otherwiseCallback),\n conditions: this.#conditionals.map((conditional) => conditional[PARSE](refs, options)),\n }\n }\n}", "score": 47.071845433415085 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " otherwise(callback: UnionNoMatchCallback<Record<string, unknown>>): this {\n this.#otherwiseCallback = callback\n return this\n }\n /**\n * Compiles the group\n */\n [PARSE](refs: RefsStore, options: ParserOptions): ObjectGroupNode {\n return {\n type: 'group',", "score": 35.27704508695702 } ]
typescript
ParserOptions): ObjectGroupNode['conditions'][number] {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { enumRule } from './rules.js' import { BaseLiteralType } from '../base/literal.js' import type { FieldContext, FieldOptions, Validation } from '../../types.js' /** * VineEnum represents a enum data type that performs validation * against a pre-defined choices list. */ export class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType< Values[number], Values[number] > { /** * Default collection of enum rules */ static rules = { enum: enumRule, } #values: Values | ((field: FieldContext) => Values) /** * Returns the enum choices */ getChoices() { return this.#values } constructor( values: Values | ((field: FieldContext) => Values), options?: FieldOptions, validations?: Validation<any>[] ) { super(
options, validations || [enumRule({ choices: values })]) this.#values = values }
/** * Clones the VineEnum schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/enum/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " Values[keyof Values]\n> {\n /**\n * Default collection of enum rules\n */\n static rules = {\n enum: enumRule,\n }\n #values: Values\n constructor(values: Values, options?: FieldOptions, validations?: Validation<any>[]) {", "score": 59.81563079347057 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define a field whose value matches the enum choices.\n */\n enum<const Values extends readonly unknown[]>(\n values: Values | ((field: FieldContext) => Values)\n ): VineEnum<Values>\n enum<Values extends EnumLike>(values: Values): VineNativeEnum<Values>\n enum<Values extends readonly unknown[] | EnumLike>(values: Values): any {\n if (Array.isArray(values) || typeof values === 'function') {", "score": 47.84501037097422 }, { "filename": "src/schema/enum/native_enum.ts", "retrieved_chunk": " super(options, validations || [enumRule({ choices: Object.values(values) })])\n this.#values = values\n }\n /**\n * Clones the VineNativeEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNativeEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }", "score": 40.63129320134726 }, { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 27.178424805709692 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 26.410999970507774 } ]
typescript
options, validations || [enumRule({ choices: values })]) this.#values = values }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(
properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 59.846527473878005 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 56.40679861482633 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 52.75585928977871 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 50.14314252647717 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 48.83687003956697 } ]
typescript
properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ( !helpers.isDecimal(String(value), { force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) {
field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) }
}) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/main.ts", "retrieved_chunk": " * of decimal places\n */\n decimal(range: number | [number, number]) {\n return this.use(decimalRule({ range: Array.isArray(range) ? range : [range] }))\n }\n /**\n * Enforce the value to be an integer (aka without decimals)\n */\n withoutDecimals() {\n return this.use(withoutDecimalsRule())", "score": 38.84907392333297 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " static rules = {\n max: maxRule,\n min: minRule,\n range: rangeRule,\n number: numberRule,\n decimal: decimalRule,\n negative: negativeRule,\n positive: positiveRule,\n withoutDecimals: withoutDecimalsRule,\n };", "score": 27.664048224055083 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * Enforce value to be within the range of minimum and maximum output.\n */\n range(value: [min: number, max: number]) {\n return this.use(rangeRule({ min: value[0], max: value[1] }))\n }\n /**\n * Enforce the value be a positive number\n */\n positive() {", "score": 26.152032864686653 }, { "filename": "src/defaults.ts", "retrieved_chunk": " 'hexCode': 'The {{ field }} field must be a valid hex color code',\n 'boolean': 'The value must be a boolean',\n 'number': 'The {{ field }} field must be a number',\n 'min': 'The {{ field }} field must be at least {{ min }}',\n 'max': 'The {{ field }} field must not be greater than {{ max }}',\n 'range': 'The {{ field }} field must be between {{ min }} and {{ max }}',\n 'positive': 'The {{ field }} field must be positive',\n 'negative': 'The {{ field }} field must be negative',\n 'decimal': 'The {{ field }} field must have {{ digits }} decimal places',\n 'withoutDecimals': 'The {{ field }} field must be an integer',", "score": 22.517637624683793 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length <= 0) {\n field.report(messages.notEmpty, 'notEmpty', field)\n }\n})\n/**", "score": 18.311327620617902 } ]
typescript
field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) }
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor
(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return Array.isArray(value)\n }\n constructor(schemas: [...Schema], options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)", "score": 59.846527473878005 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.object';\n /**\n * Checks if the value is of object type. The method must be\n * implemented for \"unionOfTypes\"\n */", "score": 56.40679861482633 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Checks if the value is of string type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n return typeof value === 'string'\n }\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations || [stringRule()])\n }", "score": 52.75585928977871 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " #schema: Schema;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.array';\n /**\n * Checks if the value is of array type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {", "score": 50.14314252647717 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.number';\n /**\n * Checks if the value is of number type. The method must be\n * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsNumber = helpers.asNumber(value)", "score": 48.83687003956697 } ]
typescript
(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { helpers } from '../../vine/helpers.js' import { createRule } from '../../vine/create_rule.js' import { messages } from '../../defaults.js' /** * Enforce the value to be a number or a string representation * of a number */ export const numberRule = createRule<{ strict?: boolean }>((value, options, field) => { const valueAsNumber = options.strict ? value : helpers.asNumber(value) if ( typeof valueAsNumber !== 'number' || Number.isNaN(valueAsNumber) || valueAsNumber === Number.POSITIVE_INFINITY || valueAsNumber === Number.NEGATIVE_INFINITY ) { field.report(messages.number, 'number', field) return } field.mutate(valueAsNumber, field) }) /** * Enforce a minimum value on a number field */ export const minRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min) { field.report(messages.min, 'min', field, options) } }) /** * Enforce a maximum value on a number field */ export const maxRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) > options.max) { field.report(messages.max, 'max', field, options) } }) /** * Enforce a range of values on a number field. */ export const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < options.min || (value as number) > options.max) { field.report(messages.range, 'range', field, options) } }) /** * Enforce the value is a positive number */ export const positiveRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) < 0) { field.report(messages.positive, 'positive', field) } }) /** * Enforce the value is a negative number */ export const negativeRule = createRule<undefined>((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as number) >= 0) { field.report(messages.negative, 'negative', field) } }) /** * Enforce the value to have a fixed or range of decimals */ export const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (
!helpers.isDecimal(String(value), {
force_decimal: options.range[0] !== 0, decimal_digits: options.range.join(','), }) ) { field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') }) } }) /** * Enforce the value to not have decimal places */ export const withoutDecimalsRule = createRule((value, _, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!Number.isInteger(value)) { field.report(messages.withoutDecimals, 'withoutDecimals', field) } })
src/schema/number/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 33.53382923240975 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 33.53382923240975 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "})\n/**\n * Enforce a maximum length on a string field\n */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 32.03496931273578 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": "export const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length < options.min) {\n field.report(messages.minLength, 'minLength', field, options)\n }", "score": 31.628503641898604 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 30.45850993314543 } ]
typescript
!helpers.isDecimal(String(value), {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject
<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 48.02846241285064 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 45.06627113444823 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " */\nexport class SchemaBuilder extends Macroable {\n /**\n * Define a sub-object as a union\n */\n group = group\n /**\n * Define a union value\n */\n union = union", "score": 42.06698806358266 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 39.48417211091283 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Represents a union conditional type. A conditional is a predicate\n * with a schema\n */\nexport class UnionConditional<Schema extends SchemaTypes> {\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n /**\n * Properties to merge when conditonal is true", "score": 36.81379102507273 } ]
typescript
<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties,
validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n allowUnknownProperties: this.#allowUnknownProperties,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n properties: this.#schemas.map((schema, index) => schema[PARSE](String(index), refs, options)),\n }\n }\n}", "score": 88.44722780569047 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,\n each: this.#schema[PARSE]('*', refs, options),\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 82.74503837603847 }, { "filename": "src/schema/array/main.ts", "retrieved_chunk": " * Compiles to array data type\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ArrayNode {\n return {\n type: 'array',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,\n isOptional: this.options.isOptional,", "score": 82.53246556813954 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " /**\n * Compiles the schema type to a compiler node\n */\n [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode {\n return {\n type: 'literal',\n fieldName: propertyName,\n propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName,\n bail: this.options.bail,\n allowNull: this.options.allowNull,", "score": 71.66234400474815 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " isOptional: this.options.isOptional,\n parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined,\n validations: this.compileValidations(refs),\n }\n }\n}", "score": 68.79084302361782 } ]
typescript
validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group )
: VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) { cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/object/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Group conditional represents a sub-set of object wrapped\n * inside a conditional\n */\nexport class GroupConditional<\n Properties extends Record<string, SchemaTypes>,\n Output,\n CamelCaseOutput,\n> {", "score": 48.02846241285064 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": "import { GroupConditional } from './conditional.js'\nimport { OTYPE, COTYPE, PARSE } from '../../symbols.js'\nimport type { ParserOptions, UnionNoMatchCallback } from '../../types.js'\n/**\n * Object group represents a group with multiple conditionals, where each\n * condition returns a set of object properties to merge into the\n * existing object.\n */\nexport class ObjectGroup<Conditional extends GroupConditional<any, any, any>> {\n declare [OTYPE]: Conditional[typeof OTYPE];", "score": 45.06627113444823 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " */\nexport class SchemaBuilder extends Macroable {\n /**\n * Define a sub-object as a union\n */\n group = group\n /**\n * Define a union value\n */\n union = union", "score": 42.06698806358266 }, { "filename": "src/schema/builder.ts", "retrieved_chunk": " }\n /**\n * Define an object with known properties. You may call \"allowUnknownProperties\"\n * to merge unknown properties.\n */\n object<Properties extends Record<string, SchemaTypes>>(properties: Properties) {\n return new VineObject<\n Properties,\n {\n [K in keyof Properties]: Properties[K][typeof OTYPE]", "score": 39.48417211091283 }, { "filename": "src/schema/union/conditional.ts", "retrieved_chunk": "import type { ParserOptions, SchemaTypes } from '../../types.js'\n/**\n * Represents a union conditional type. A conditional is a predicate\n * with a schema\n */\nexport class UnionConditional<Schema extends SchemaTypes> {\n declare [OTYPE]: Schema[typeof OTYPE];\n declare [COTYPE]: Schema[typeof COTYPE]\n /**\n * Properties to merge when conditonal is true", "score": 36.81379102507273 } ]
typescript
: VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import camelcase from 'camelcase' import type { ObjectNode, RefsStore } from '@vinejs/compiler/types' import { ObjectGroup } from './group.js' import { GroupConditional } from './conditional.js' import { BaseModifiersType, BaseType } from '../base/main.js' import { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js' import type { Validation, SchemaTypes, FieldOptions, ParserOptions } from '../../types.js' /** * Converts schema properties to camelCase */ export class VineCamelCaseObject< Schema extends VineObject<any, any, any>, > extends BaseModifiersType<Schema[typeof COTYPE], Schema[typeof COTYPE]> { #schema: Schema; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'types.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(schema: Schema) { super() this.#schema = schema } /** * Clone object */ clone(): this { return new VineCamelCaseObject<Schema>(this.#schema.clone()) as this } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { options.toCamelCase = true return this.#schema[PARSE](propertyName, refs, options) } } /** * VineObject represents an object value in the validation * schema. */ export class VineObject< Properties extends Record<string, SchemaTypes>, Output, CamelCaseOutput, > extends BaseType<Output, CamelCaseOutput> { /** * Object properties */ #properties: Properties /** * Object groups to merge based on conditionals */ #groups: ObjectGroup<GroupConditional<any, any, any>>[] = [] /** * Whether or not to allow unknown properties */ #allowUnknownProperties: boolean = false; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.object'; /** * Checks if the value is of object type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return value !== null && typeof value === 'object' && !Array.isArray(value) } constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations) this.#properties = properties } /** * Returns a clone copy of the object properties. The object groups * are not copied to keep the implementations simple and easy to * reason about. */ getProperties(): Properties { return Object.keys(this.#properties).reduce((result, key) => { result[key as keyof Properties] = this.#properties[ key ].clone() as Properties[keyof Properties] return result }, {} as Properties) } /** * Copy unknown properties to the final output. */ allowUnknownProperties<Value>(): VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > { this.#allowUnknownProperties = true return this as VineObject< Properties, Output & { [K: string]: Value }, CamelCaseOutput & { [K: string]: Value } > } /** * Merge a union to the object groups. The union can be a "vine.union" * with objects, or a "vine.object.union" with properties. */ merge<Group extends ObjectGroup<GroupConditional<any, any, any>>>( group: Group ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> { this.#groups.push(group) return this as VineObject< Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE] > } /** * Clone object */ clone(): this { const cloned = new VineObject<Properties, Output, CamelCaseOutput>( this.getProperties(), this.cloneOptions(), this.
cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
cloned.allowUnknownProperties() } return cloned as this } /** * Applies camelcase transform */ toCamelCase() { return new VineCamelCaseObject(this) } /** * Compiles the schema type to a compiler node */ [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): ObjectNode { return { type: 'object', fieldName: propertyName, propertyName: options.toCamelCase ? camelcase(propertyName) : propertyName, bail: this.options.bail, allowNull: this.options.allowNull, isOptional: this.options.isOptional, parseFnId: this.options.parse ? refs.trackParser(this.options.parse) : undefined, allowUnknownProperties: this.#allowUnknownProperties, validations: this.compileValidations(refs), properties: Object.keys(this.#properties).map((property) => { return this.#properties[property][PARSE](property, refs, options) }), groups: this.#groups.map((group) => { return group[PARSE](refs, options) }), } } }
src/schema/object/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/tuple/main.ts", "retrieved_chunk": " clone(): this {\n const cloned = new VineTuple<Schema, Output, CamelCaseOutput>(\n this.#schemas.map((schema) => schema.clone()) as Schema,\n this.cloneOptions(),\n this.cloneValidations()\n )\n if (this.#allowUnknownProperties) {\n cloned.allowUnknownProperties()\n }\n return cloned as this", "score": 48.10652609795903 }, { "filename": "src/schema/object/group.ts", "retrieved_chunk": " */\n clone(): this {\n const cloned = new ObjectGroup<Conditional>(this.#conditionals)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this\n }\n /**\n * Define a fallback method to invoke when all of the group conditions\n * fail. You may use this method to report an error.\n */", "score": 30.961240373612828 }, { "filename": "src/schema/union_of_types/main.ts", "retrieved_chunk": " return this\n }\n /**\n * Clones the VineUnionOfTypes schema type.\n */\n clone(): this {\n const cloned = new VineUnionOfTypes<Schema>(this.#schemas)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this\n }", "score": 27.8885810195743 }, { "filename": "src/schema/union/main.ts", "retrieved_chunk": " this.#otherwiseCallback = callback\n return this\n }\n /**\n * Clones the VineUnion schema type.\n */\n clone(): this {\n const cloned = new VineUnion<Conditional>(this.#conditionals)\n cloned.otherwise(this.#otherwiseCallback)\n return cloned as this", "score": 27.277363029621053 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " clone(): this {\n return new VineString(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 22.083165696774525 } ]
typescript
cloneValidations() ) this.#groups.forEach((group) => cloned.merge(group)) if (this.#allowUnknownProperties) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) { return this.use(urlRule(...args)) } /** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this {
return new VineString(this.cloneOptions(), this.cloneValidations()) as this }
}
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/main.ts", "retrieved_chunk": " return this.use(compactRule())\n }\n /**\n * Clones the VineArray schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineArray(this.#schema.clone(), this.cloneOptions(), this.cloneValidations()) as this\n }\n /**", "score": 53.50426774515303 }, { "filename": "src/schema/number/main.ts", "retrieved_chunk": " }\n /**\n * Clones the VineNumber schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineNumber(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 53.124296793040756 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " }\n /**\n * Clones the VineRecord schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineRecord(\n this.#schema.clone(),\n this.cloneOptions(),\n this.cloneValidations()", "score": 52.89136358164784 }, { "filename": "src/schema/enum/main.ts", "retrieved_chunk": " /**\n * Clones the VineEnum schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineEnum(this.#values, this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 51.94637385161264 }, { "filename": "src/schema/boolean/main.ts", "retrieved_chunk": " super(options, validations || [booleanRule(options || {})])\n }\n /**\n * Clones the VineBoolean schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineBoolean(this.cloneOptions(), this.cloneValidations()) as this\n }\n}", "score": 51.14501886206624 } ]
typescript
return new VineString(this.cloneOptions(), this.cloneValidations()) as this }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return }
if (!helpers.isEmail(value as string, options)) {
field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(activeUrlRule())\n }\n /**\n * Validates the value to be a valid email address\n */\n email(...args: Parameters<typeof emailRule>) {\n return this.use(emailRule(...args))\n }\n /**\n * Validates the value to be a valid mobile number", "score": 34.25256139790913 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 30.986206413135903 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 29.154406592930073 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 29.097230962482136 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 28.96945026508995 } ]
typescript
if (!helpers.isEmail(value as string, options)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) { field.report(messages['record.maxLength'], 'record.maxLength', field, options) } }) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) {
field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) }
}) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>( (value, callback, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 55.11710846681888 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 45.74270519530937 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length <= 0) {\n field.report(messages.notEmpty, 'notEmpty', field)\n }\n})\n/**", "score": 41.5188037957075 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 40.0688252010125 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 36.80519437487833 } ]
typescript
field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any'
if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) {
field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 37.402275126406565 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 36.7228260352761 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 36.540030283126995 }, { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": "import { FieldContext } from '@vinejs/compiler/types'\n/**\n * Enum rule is used to validate the field's value to be one\n * from the pre-defined choices.\n */\nexport const enumRule = createRule<{\n choices: readonly any[] | ((field: FieldContext) => readonly any[])\n}>((value, options, field) => {\n const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices\n /**", "score": 34.29015461393948 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Ensure array elements are distinct/unique\n */\nexport const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**", "score": 33.509552813868574 } ]
typescript
if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) {
field.report(messages['record.maxLength'], 'record.maxLength', field, options) }
}) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) { field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) } }) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>( (value, callback, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 42.30187399720757 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length <= 0) {\n field.report(messages.notEmpty, 'notEmpty', field)\n }\n})\n/**", "score": 41.5188037957075 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 40.0688252010125 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 39.936687659820585 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\n if ((value as unknown[]).length > options.max) {\n field.report(messages['array.maxLength'], 'array.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an array field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 35.27433661042356 } ]
typescript
field.report(messages['record.maxLength'], 'record.maxLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (
!helpers.isHexColor(value as string)) {
field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 35.571068029832794 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "/**\n * Enforce the value is a positive number\n */\nexport const positiveRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }", "score": 30.88210256951727 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " /**\n * Check if the value is a valid color hexcode\n */\n isHexColor: (value: string) => {\n if (!value.startsWith('#')) {\n return false\n }\n return isHexColor.default(value)\n },\n /**", "score": 29.847274016908962 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 29.608049735579282 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 29.065566784595433 } ]
typescript
!helpers.isHexColor(value as string)) {
/* * vinejs * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { BaseLiteralType } from '../base/literal.js' import { IS_OF_TYPE, UNIQUE_NAME } from '../../symbols.js' import type { Validation, AlphaOptions, FieldContext, FieldOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import { inRule, urlRule, uuidRule, trimRule, alphaRule, emailRule, notInRule, regexRule, sameAsRule, mobileRule, escapeRule, stringRule, hexCodeRule, passportRule, endsWithRule, ipAddressRule, confirmedRule, notSameAsRule, activeUrlRule, minLengthRule, maxLengthRule, startsWithRule, creditCardRule, postalCodeRule, fixedLengthRule, alphaNumericRule, normalizeEmailRule, asciiRule, ibanRule, jwtRule, coordinatesRule, toUpperCaseRule, toLowerCaseRule, toCamelCaseRule, normalizeUrlRule, } from './rules.js' /** * VineString represents a string value in the validation schema. */ export class VineString extends BaseLiteralType<string, string> { static rules = { in: inRule, jwt: jwtRule, url: urlRule, iban: ibanRule, uuid: uuidRule, trim: trimRule, email: emailRule, alpha: alphaRule, ascii: asciiRule, notIn: notInRule, regex: regexRule, escape: escapeRule, sameAs: sameAsRule, mobile: mobileRule, string: stringRule, hexCode: hexCodeRule, passport: passportRule, endsWith: endsWithRule, confirmed: confirmedRule, activeUrl: activeUrlRule, minLength: minLengthRule, notSameAs: notSameAsRule, maxLength: maxLengthRule, ipAddress: ipAddressRule, creditCard: creditCardRule, postalCode: postalCodeRule, startsWith: startsWithRule, toUpperCase: toUpperCaseRule, toLowerCase: toLowerCaseRule, toCamelCase: toCamelCaseRule, fixedLength: fixedLengthRule, coordinates: coordinatesRule, normalizeUrl: normalizeUrlRule, alphaNumeric: alphaNumericRule, normalizeEmail: normalizeEmailRule, }; /** * The property must be implemented for "unionOfTypes" */ [UNIQUE_NAME] = 'vine.string'; /** * Checks if the value is of string type. The method must be * implemented for "unionOfTypes" */ [IS_OF_TYPE] = (value: unknown) => { return typeof value === 'string' } constructor(options?: FieldOptions, validations?: Validation<any>[]) { super(options, validations || [stringRule()]) } /** * Validates the value to be a valid URL */ url(...args: Parameters<typeof urlRule>) {
return this.use(urlRule(...args)) }
/** * Validates the value to be an active URL */ activeUrl() { return this.use(activeUrlRule()) } /** * Validates the value to be a valid email address */ email(...args: Parameters<typeof emailRule>) { return this.use(emailRule(...args)) } /** * Validates the value to be a valid mobile number */ mobile(...args: Parameters<typeof mobileRule>) { return this.use(mobileRule(...args)) } /** * Validates the value to be a valid IP address. */ ipAddress(version?: 4 | 6) { return this.use(ipAddressRule(version ? { version } : undefined)) } /** * Validates the value to be a valid hex color code */ hexCode() { return this.use(hexCodeRule()) } /** * Validates the value to be an active URL */ regex(expression: RegExp) { return this.use(regexRule(expression)) } /** * Validates the value to contain only letters */ alpha(options?: AlphaOptions) { return this.use(alphaRule(options)) } /** * Validates the value to contain only letters and * numbers */ alphaNumeric(options?: AlphaNumericOptions) { return this.use(alphaNumericRule(options)) } /** * Enforce a minimum length on a string field */ minLength(expectedLength: number) { return this.use(minLengthRule({ min: expectedLength })) } /** * Enforce a maximum length on a string field */ maxLength(expectedLength: number) { return this.use(maxLengthRule({ max: expectedLength })) } /** * Enforce a fixed length on a string field */ fixedLength(expectedLength: number) { return this.use(fixedLengthRule({ size: expectedLength })) } /** * Ensure the field under validation is confirmed by * having another field with the same name. */ confirmed(options?: { confirmationField: string }) { return this.use(confirmedRule(options)) } /** * Trims whitespaces around the string value */ trim() { return this.use(trimRule()) } /** * Normalizes the email address */ normalizeEmail(options?: NormalizeEmailOptions) { return this.use(normalizeEmailRule(options)) } /** * Converts the field value to UPPERCASE. */ toUpperCase() { return this.use(toUpperCaseRule()) } /** * Converts the field value to lowercase. */ toLowerCase() { return this.use(toLowerCaseRule()) } /** * Converts the field value to camelCase. */ toCamelCase() { return this.use(toCamelCaseRule()) } /** * Escape string for HTML entities */ escape() { return this.use(escapeRule()) } /** * Normalize a URL */ normalizeUrl(...args: Parameters<typeof normalizeUrlRule>) { return this.use(normalizeUrlRule(...args)) } /** * Ensure the value starts with the pre-defined substring */ startsWith(substring: string) { return this.use(startsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ endsWith(substring: string) { return this.use(endsWithRule({ substring })) } /** * Ensure the value ends with the pre-defined substring */ sameAs(otherField: string) { return this.use(sameAsRule({ otherField })) } /** * Ensure the value ends with the pre-defined substring */ notSameAs(otherField: string) { return this.use(notSameAsRule({ otherField })) } /** * Ensure the field's value under validation is a subset of the pre-defined list. */ in(choices: string[] | ((field: FieldContext) => string[])) { return this.use(inRule({ choices })) } /** * Ensure the field's value under validation is not inside the pre-defined list. */ notIn(list: string[] | ((field: FieldContext) => string[])) { return this.use(notInRule({ list })) } /** * Validates the value to be a valid credit card number */ creditCard(...args: Parameters<typeof creditCardRule>) { return this.use(creditCardRule(...args)) } /** * Validates the value to be a valid passport number */ passport(...args: Parameters<typeof passportRule>) { return this.use(passportRule(...args)) } /** * Validates the value to be a valid postal code */ postalCode(...args: Parameters<typeof postalCodeRule>) { return this.use(postalCodeRule(...args)) } /** * Validates the value to be a valid UUID */ uuid(...args: Parameters<typeof uuidRule>) { return this.use(uuidRule(...args)) } /** * Validates the value contains ASCII characters only */ ascii() { return this.use(asciiRule()) } /** * Validates the value to be a valid IBAN number */ iban() { return this.use(ibanRule()) } /** * Validates the value to be a valid JWT token */ jwt() { return this.use(jwtRule()) } /** * Ensure the value is a string with latitude and longitude coordinates */ coordinates() { return this.use(coordinatesRule()) } /** * Clones the VineString schema type. The applied options * and validations are copied to the new instance */ clone(): this { return new VineString(this.cloneOptions(), this.cloneValidations()) as this } }
src/schema/string/main.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/base/main.ts", "retrieved_chunk": " protected options: FieldOptions\n /**\n * Set of validations to run\n */\n protected validations: Validation<any>[]\n constructor(options?: FieldOptions, validations?: Validation<any>[]) {\n super()\n this.options = options || {\n bail: true,\n allowNull: false,", "score": 27.39946990235522 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if (!helpers.isHexColor(value as string)) {\n field.report(messages.hexCode, 'hexCode', field)\n }\n})\n/**\n * Validates the value to be a valid URL\n */\nexport const urlRule = createRule<URLOptions | undefined>((value, options, field) => {\n if (!field.isValid) {", "score": 26.68404305395138 }, { "filename": "src/schema/record/main.ts", "retrieved_chunk": " * Enforce a fixed length on an object field\n */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Register a callback to validate the object keys\n */\n validateKeys(...args: Parameters<typeof validateKeysRule>) {\n return this.use(validateKeysRule(...args))", "score": 26.048380981668252 }, { "filename": "src/schema/base/literal.ts", "retrieved_chunk": " */\n protected validations: Validation<any>[]\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super()\n this.options = {\n bail: true,\n allowNull: false,\n isOptional: false,\n ...options,\n }", "score": 25.748119204512783 }, { "filename": "src/schema/any/main.ts", "retrieved_chunk": "/**\n * VineAny represents a value that can be anything\n */\nexport class VineAny extends BaseLiteralType<any, any> {\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super(options, validations)\n }\n /**\n * Clones the VineAny schema type. The applied options\n * and validations are copied to the new instance", "score": 25.513320182201696 } ]
typescript
return this.use(urlRule(...args)) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (
!helpers.isIP(value as string, options?.version)) {
field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n mobile(...args: Parameters<typeof mobileRule>) {\n return this.use(mobileRule(...args))\n }\n /**\n * Validates the value to be a valid IP address.\n */\n ipAddress(version?: 4 | 6) {\n return this.use(ipAddressRule(version ? { version } : undefined))\n }", "score": 58.49483143440209 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 30.986206413135903 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 29.154406592930073 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 29.097230962482136 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 28.96945026508995 } ]
typescript
!helpers.isIP(value as string, options?.version)) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { FieldContext } from '@vinejs/compiler/types' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' /** * Enforce a minimum length on an object field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length < options.min) { field.report(messages['record.minLength'], 'record.minLength', field, options) } }) /** * Enforce a maximum length on an object field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length > options.max) { field.report(messages['record.maxLength'], 'record.maxLength', field, options) } }) /** * Enforce a fixed length on an object field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } /** * Value will always be an object if the field is valid. */ if (Object.keys(value as Record<string, any>).length !== options.size) { field.report(messages['record.fixedLength'], 'record.fixedLength', field, options) } }) /** * Register a callback to validate the object keys */ export const validateKeysRule = createRule<(keys: string[], field: FieldContext) => void>(
(value, callback, field) => {
/** * Skip if the field is not valid. */ if (!field.isValid) { return } callback(Object.keys(value as Record<string, any>), field) } )
src/schema/record/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/record/main.ts", "retrieved_chunk": " * Enforce a fixed length on an object field\n */\n fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Register a callback to validate the object keys\n */\n validateKeys(...args: Parameters<typeof validateKeysRule>) {\n return this.use(validateKeysRule(...args))", "score": 54.72469711921754 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as string).length !== options.size) {\n field.report(messages.fixedLength, 'fixedLength', field, options)\n }\n})\n/**", "score": 37.32519650765162 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length !== options.size) {\n field.report(messages['array.fixedLength'], 'array.fixedLength', field, options)", "score": 31.6069140115734 }, { "filename": "src/schema/string/rules.ts", "retrieved_chunk": " }\n if ((value as string).length > options.max) {\n field.report(messages.maxLength, 'maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on a string field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 30.547226419362982 }, { "filename": "src/defaults.ts", "retrieved_chunk": " 'record': 'The {{ field }} field must be an object',\n 'record.minLength': 'The {{ field }} field must have at least {{ min }} items',\n 'record.maxLength': 'The {{ field }} field must not have more than {{ max }} items',\n 'record.fixedLength': 'The {{ field }} field must contain {{ size }} items',\n 'tuple': 'The {{ field }} field must be an array',\n 'union': 'Invalid value provided for {{ field }} field',\n 'unionGroup': 'Invalid value provided for {{ field }} field',\n 'unionOfTypes': 'Invalid value provided for {{ field }} field',\n}\n/**", "score": 28.902672019219878 } ]
typescript
(value, callback, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) {
field.report(messages.mobile, 'mobile', field) }
}) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 40.51582901225647 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 40.25067725148313 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 38.52567586784326 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 35.30160352291011 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\n if (Object.keys(value as Record<string, any>).length > options.max) {\n field.report(messages['record.maxLength'], 'record.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an object field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 35.11062866130382 } ]
typescript
field.report(messages.mobile, 'mobile', field) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.
regex, 'regex', field) }
}) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 43.83990657717828 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 33.038750721811695 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 32.88009544760183 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(regexRule(expression))\n }\n /**\n * Validates the value to contain only letters\n */\n alpha(options?: AlphaOptions) {\n return this.use(alphaRule(options))\n }\n /**\n * Validates the value to contain only letters and", "score": 31.233231789232025 }, { "filename": "src/schema/accepted/rules.ts", "retrieved_chunk": "export const acceptedRule = createRule((value, _, field) => {\n if (!ACCEPTED_VALUES.includes(value as any)) {\n field.report(messages.accepted, 'accepted', field)\n }\n})", "score": 30.26799789984235 } ]
typescript
regex, 'regex', field) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */
export const regexRule = createRule<RegExp>((value, expression, field) => {
if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/boolean/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Validates the value to be a boolean\n */\nexport const booleanRule = createRule<{ strict?: boolean }>((value, options, field) => {\n const valueAsBoolean = options.strict === true ? value : helpers.asBoolean(value)\n if (typeof valueAsBoolean !== 'boolean') {\n field.report(messages.boolean, 'boolean', field)\n return\n }", "score": 29.39696344141291 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid hex color code\n */\n hexCode() {\n return this.use(hexCodeRule())\n }\n /**\n * Validates the value to be an active URL\n */\n regex(expression: RegExp) {", "score": 28.414692248429127 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " return this.use(regexRule(expression))\n }\n /**\n * Validates the value to contain only letters\n */\n alpha(options?: AlphaOptions) {\n return this.use(alphaRule(options))\n }\n /**\n * Validates the value to contain only letters and", "score": 27.332215162575523 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " */\n mobile(...args: Parameters<typeof mobileRule>) {\n return this.use(mobileRule(...args))\n }\n /**\n * Validates the value to be a valid IP address.\n */\n ipAddress(version?: 4 | 6) {\n return this.use(ipAddressRule(version ? { version } : undefined))\n }", "score": 27.091506089855255 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 26.66141012260249 } ]
typescript
export const regexRule = createRule<RegExp>((value, expression, field) => {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return }
if (!(await helpers.isActiveURL(value as string))) {
field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Validates the value to be a valid URL\n */\n url(...args: Parameters<typeof urlRule>) {\n return this.use(urlRule(...args))\n }\n /**\n * Validates the value to be an active URL\n */\n activeUrl() {", "score": 27.89805482601548 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "/**\n * Enforce the value is a positive number\n */\nexport const positiveRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }", "score": 27.518322949808915 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 27.291748489154802 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " * Check if a URL has valid `A` or `AAAA` DNS records\n */\n isActiveURL: async (url: string): Promise<boolean> => {\n try {\n const { hostname } = new URL(url)\n const v6Addresses = await resolve6(hostname)\n if (v6Addresses.length) {\n return true\n /* c8 ignore next 4 */\n } else {", "score": 26.707655782611752 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const decimalRule = createRule<{ range: [number, number?] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (\n !helpers.isDecimal(String(value), {", "score": 26.6757401863619 } ]
typescript
if (!(await helpers.isActiveURL(value as string))) {
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) {
field.report(messages.minLength, 'minLength', field, options) }
}) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 63.006031563977 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 55.147169359829654 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an object field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 53.565750060201246 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Enforce a minimum length on an array field\n */\nexport const minLengthRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return", "score": 53.565750060201246 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " }\n /**\n * Value will always be an array if the field is valid.\n */\n if ((value as unknown[]).length < options.min) {\n field.report(messages['array.minLength'], 'array.minLength', field, options)\n }\n})\n/**\n * Enforce a maximum length on an array field", "score": 51.275778365594135 } ]
typescript
field.report(messages.minLength, 'minLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) {
field.report(messages.startsWith, 'startsWith', field, options) }
}) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 49.60640187660037 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 46.321084496440626 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": "export const withoutDecimalsRule = createRule((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if (!Number.isInteger(value)) {\n field.report(messages.withoutDecimals, 'withoutDecimals', field)\n }", "score": 46.14620891098569 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Ensure array elements are distinct/unique\n */\nexport const distinctRule = createRule<{ fields?: string | string[] }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**", "score": 45.001478276441475 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.\n */\n if (Object.keys(value as Record<string, any>).length !== options.size) {\n field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)", "score": 44.094813662109914 } ]
typescript
field.report(messages.startsWith, 'startsWith', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) {
field.report(messages.maxLength, 'maxLength', field, options) }
}) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 55.147169359829654 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an object if the field is valid.", "score": 54.87668863645269 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\nexport const maxLengthRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n /**\n * Value will always be an array if the field is valid.", "score": 54.87668863645269 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " */\n if ((value as unknown[]).length > options.max) {\n field.report(messages['array.maxLength'], 'array.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an array field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 54.023620804487166 }, { "filename": "src/schema/record/rules.ts", "retrieved_chunk": " */\n if (Object.keys(value as Record<string, any>).length > options.max) {\n field.report(messages['record.maxLength'], 'record.maxLength', field, options)\n }\n})\n/**\n * Enforce a fixed length on an object field\n */\nexport const fixedLengthRule = createRule<{ size: number }>((value, options, field) => {\n /**", "score": 52.788264197466525 } ]
typescript
field.report(messages.maxLength, 'maxLength', field, options) }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages
.sameAs, 'sameAs', field, options) return }
}) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " */\n if (typeof options.expectedValue === 'boolean') {\n input = helpers.asBoolean(value)\n } else if (typeof options.expectedValue === 'number') {\n input = helpers.asNumber(value)\n }\n /**\n * Performing validation and reporting error\n */\n if (input !== options.expectedValue) {", "score": 36.295805879504314 }, { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " field.report(messages.literal, 'literal', field, options)\n return\n }\n /**\n * Mutating input with normalized value\n */\n field.mutate(input, field)\n})", "score": 27.712198694696383 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " */\nexport const minRule = createRule<{ min: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min) {\n field.report(messages.min, 'min', field, options)", "score": 19.484992530114106 }, { "filename": "src/defaults.ts", "retrieved_chunk": " 'fixedLength': 'The {{ field }} field must be {{ size }} characters long',\n 'confirmed': 'The {{ field }} field and {{ otherField }} field must be the same',\n 'endsWith': 'The {{ field }} field must end with {{ substring }}',\n 'startsWith': 'The {{ field }} field must start with {{ substring }}',\n 'sameAs': 'The {{ field }} field and {{ otherField }} field must be the same',\n 'notSameAs': 'The {{ field }} field and {{ otherField }} field must be different',\n 'in': 'The selected {{ field }} is invalid',\n 'notIn': 'The selected {{ field }} is invalid',\n 'ipAddress': 'The {{ field }} field must be a valid IP address',\n 'uuid': 'The {{ field }} field must be a valid UUID',", "score": 19.202610835719238 }, { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 18.82861669934074 } ]
typescript
.sameAs, 'sameAs', field, options) return }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(
messages.in, 'in', field, options) return }
} ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": " * Report error when value is not part of the pre-defined\n * options\n */\n if (!choices.includes(value)) {\n field.report(messages.enum, 'enum', field, { choices })\n }\n})", "score": 53.35483533450178 }, { "filename": "src/schema/enum/rules.ts", "retrieved_chunk": "import { FieldContext } from '@vinejs/compiler/types'\n/**\n * Enum rule is used to validate the field's value to be one\n * from the pre-defined choices.\n */\nexport const enumRule = createRule<{\n choices: readonly any[] | ((field: FieldContext) => readonly any[])\n}>((value, options, field) => {\n const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices\n /**", "score": 51.13137096671151 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Ensure the value ends with the pre-defined substring\n */\n notSameAs(otherField: string) {\n return this.use(notSameAsRule({ otherField }))\n }\n /**\n * Ensure the field's value under validation is a subset of the pre-defined list.\n */\n in(choices: string[] | ((field: FieldContext) => string[])) {", "score": 30.741041084346598 }, { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " */\n if (typeof options.expectedValue === 'boolean') {\n input = helpers.asBoolean(value)\n } else if (typeof options.expectedValue === 'number') {\n input = helpers.asNumber(value)\n }\n /**\n * Performing validation and reporting error\n */\n if (input !== options.expectedValue) {", "score": 30.705854471104686 }, { "filename": "src/schema/enum/main.ts", "retrieved_chunk": " return this.#values\n }\n constructor(\n values: Values | ((field: FieldContext) => Values),\n options?: FieldOptions,\n validations?: Validation<any>[]\n ) {\n super(options, validations || [enumRule({ choices: values })])\n this.#values = values\n }", "score": 30.041418932449652 } ]
typescript
messages.in, 'in', field, options) return }
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.confirmed, 'confirmed', field, { otherField }) return } } ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else {
const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " * Value will always be an array if the field is valid.\n */\n if (!helpers.isDistinct(value as any[], options.fields)) {\n field.report(messages.distinct, 'distinct', field, options)\n }\n})\n/**\n * Removes empty strings, null and undefined values from the array\n */\nexport const compactRule = createRule<undefined>((value, _, field) => {", "score": 22.123555615180287 }, { "filename": "src/schema/accepted/rules.ts", "retrieved_chunk": "export const acceptedRule = createRule((value, _, field) => {\n if (!ACCEPTED_VALUES.includes(value as any)) {\n field.report(messages.accepted, 'accepted', field)\n }\n})", "score": 21.915852054879874 }, { "filename": "src/vine/helpers.ts", "retrieved_chunk": " if (helpers.isObject(item) && helpers.hasKeys(item, fieldsList)) {\n const element = fieldsList.map((field) => item[field]).join('_')\n if (uniqueItems.has(element)) {\n return false\n } else {\n uniqueItems.add(element)\n }\n }\n }\n return true", "score": 21.336245355967996 }, { "filename": "src/schema/number/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n if ((value as number) < options.min || (value as number) > options.max) {\n field.report(messages.range, 'range', field, options)\n }\n})", "score": 21.18357008442297 }, { "filename": "src/schema/array/rules.ts", "retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n field.mutate(\n (value as unknown[]).filter((item) => helpers.exists(item) && item !== ''),\n field\n )", "score": 20.903249187902958 } ]
typescript
const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) {
import get from 'lodash.get'; import { CloudWatch } from '@aws-sdk/client-cloudwatch'; import { CloudWatchLogs, DescribeLogGroupsCommandOutput, LogGroup } from '@aws-sdk/client-cloudwatch-logs'; import { AwsCredentialsProvider } from '@tinystacks/ops-aws-core-widgets'; import { ONE_GB_IN_BYTES } from '../types/constants.js'; import { AwsServiceOverrides } from '../types/types.js'; import { getHourlyCost, rateLimitMap } from '../utils/utils.js'; import { AwsServiceUtilization } from './aws-service-utilization.js'; const ONE_HUNDRED_MB_IN_BYTES = 104857600; const NOW = Date.now(); const oneMonthAgo = NOW - (30 * 24 * 60 * 60 * 1000); const thirtyDaysAgo = NOW - (30 * 24 * 60 * 60 * 1000); const sevenDaysAgo = NOW - (7 * 24 * 60 * 60 * 1000); const twoWeeksAgo = NOW - (14 * 24 * 60 * 60 * 1000); type AwsCloudwatchLogsUtilizationScenarioTypes = 'hasRetentionPolicy' | 'lastEventTime' | 'storedBytes'; const AwsCloudWatchLogsMetrics = ['IncomingBytes']; export class AwsCloudwatchLogsUtilization extends AwsServiceUtilization<AwsCloudwatchLogsUtilizationScenarioTypes> { constructor () { super(); } async doAction ( awsCredentialsProvider: AwsCredentialsProvider, actionName: string, resourceArn: string, region: string ): Promise<void> { const resourceId = resourceArn.split(':').at(-2); if (actionName === 'deleteLogGroup') { const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.deleteLogGroup(cwLogsClient, resourceId); } if(actionName === 'setRetentionPolicy'){ const cwLogsClient = new CloudWatchLogs({ credentials: await awsCredentialsProvider.getCredentials(), region }); await this.setRetentionPolicy(cwLogsClient, resourceId, 90); } } async setRetentionPolicy (cwLogsClient: CloudWatchLogs, logGroupName: string, retentionInDays: number) { await cwLogsClient.putRetentionPolicy({ logGroupName, retentionInDays }); } async deleteLogGroup (cwLogsClient: CloudWatchLogs, logGroupName: string) { await cwLogsClient.deleteLogGroup({ logGroupName }); } async createExportTask (cwLogsClient: CloudWatchLogs, logGroupName: string, bucket: string) { await cwLogsClient.createExportTask({ logGroupName, destination: bucket, from: 0, to: Date.now() }); } private async getAllLogGroups (credentials: any, region: string) { let allLogGroups: LogGroup[] = []; const cwLogsClient = new CloudWatchLogs({ credentials, region }); let describeLogGroupsRes: DescribeLogGroupsCommandOutput; do { describeLogGroupsRes = await cwLogsClient.describeLogGroups({ nextToken: describeLogGroupsRes?.nextToken }); allLogGroups = [ ...allLogGroups, ...describeLogGroupsRes?.logGroups || [] ]; } while (describeLogGroupsRes?.nextToken); return allLogGroups; } private async getEstimatedMonthlyIncomingBytes ( credentials: any, region: string, logGroupName: string, lastEventTime: number ) { if (!lastEventTime || lastEventTime < twoWeeksAgo) { return 0; } const cwClient = new CloudWatch({ credentials, region }); // total bytes over last month const res = await cwClient.getMetricData({ StartTime: new Date(oneMonthAgo), EndTime: new Date(), MetricDataQueries: [ { Id: 'incomingBytes', MetricStat: { Metric: { Namespace: 'AWS/Logs', MetricName: 'IncomingBytes', Dimensions: [{ Name: 'LogGroupName', Value: logGroupName }] }, Period: 30 * 24 * 12 * 300, // 1 month Stat: 'Sum' } } ] }); const monthlyIncomingBytes = get(res, 'MetricDataResults[0].Values[0]', 0); return monthlyIncomingBytes; } private async getLogGroupData (credentials: any, region: string, logGroup: LogGroup) { const cwLogsClient = new CloudWatchLogs({ credentials, region }); const logGroupName = logGroup?.logGroupName; // get data and cost estimate for stored bytes const storedBytes = logGroup?.storedBytes || 0; const storedBytesCost = (storedBytes / ONE_GB_IN_BYTES) * 0.03; const dataProtectionEnabled = logGroup?.dataProtectionStatus === 'ACTIVATED'; const dataProtectionCost = dataProtectionEnabled ? storedBytes * 0.12 : 0; const monthlyStorageCost = storedBytesCost + dataProtectionCost; // get data and cost estimate for ingested bytes const describeLogStreamsRes = await cwLogsClient.describeLogStreams({ logGroupName, orderBy: 'LastEventTime', descending: true, limit: 1 }); const lastEventTime = describeLogStreamsRes.logStreams[0]?.lastEventTimestamp; const estimatedMonthlyIncomingBytes = await this.getEstimatedMonthlyIncomingBytes( credentials, region, logGroupName, lastEventTime ); const logIngestionCost = (estimatedMonthlyIncomingBytes / ONE_GB_IN_BYTES) * 0.5; // get associated resource let associatedResourceId = ''; if (logGroupName.startsWith('/aws/rds')) { associatedResourceId = logGroupName.split('/')[4]; } else if (logGroupName.startsWith('/aws')) { associatedResourceId = logGroupName.split('/')[3]; } return { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost: logIngestionCost + monthlyStorageCost, associatedResourceId }; } private async getRegionalUtilization (credentials: any, region: string, _overrides?: AwsServiceOverrides) { const allLogGroups = await this.getAllLogGroups(credentials, region); const analyzeLogGroup = async (logGroup: LogGroup) => { const logGroupName = logGroup?.logGroupName; const logGroupArn = logGroup?.arn; const retentionInDays = logGroup?.retentionInDays; if (!retentionInDays) { const { storedBytes, lastEventTime, monthlyStorageCost, totalMonthlyCost, associatedResourceId } = await this.getLogGroupData(credentials, region, logGroup); this.addScenario(logGroupArn, 'hasRetentionPolicy', { value: retentionInDays?.toString(), optimize: { action: 'setRetentionPolicy', isActionable: true, reason: 'this log group does not have a retention policy', monthlySavings: monthlyStorageCost } }); // TODO: change limit compared if (storedBytes > ONE_HUNDRED_MB_IN_BYTES) { this.addScenario(logGroupArn, 'storedBytes', { value: storedBytes.toString(), scaleDown: { action: 'createExportTask', isActionable: false, reason: 'this log group has more than 100 MB of stored data', monthlySavings: monthlyStorageCost } }); } if (lastEventTime < thirtyDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), delete: { action: 'deleteLogGroup', isActionable: true, reason: 'this log group has not had an event in over 30 days', monthlySavings: totalMonthlyCost } }); } else if (lastEventTime < sevenDaysAgo) { this.addScenario(logGroupArn, 'lastEventTime', { value: new Date(lastEventTime).toLocaleString(), optimize: { isActionable: false, action: '', reason: 'this log group has not had an event in over 7 days' } }); } await this.fillData( logGroupArn, credentials, region, { resourceId: logGroupName, ...(associatedResourceId && { associatedResourceId }), region, monthlyCost: totalMonthlyCost, hourlyCost: getHourlyCost(totalMonthlyCost) } ); AwsCloudWatchLogsMetrics.forEach(async (metricName) => { await this.getSidePanelMetrics( credentials, region, logGroupArn, 'AWS/Logs', metricName, [{ Name: 'LogGroupName', Value: logGroupName }]); }); } }; await rateLimitMap(allLogGroups, 5, 5, analyzeLogGroup); } async getUtilization (
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) {
const credentials = await awsCredentialsProvider.getCredentials(); for (const region of regions) { await this.getRegionalUtilization(credentials, region, overrides); } } }
src/service-utilizations/aws-cloudwatch-logs-utilization.ts
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/service-utilizations/aws-s3-utilization.tsx", "retrieved_chunk": " );\n };\n await rateLimitMap(allS3Buckets, 5, 5, analyzeS3Bucket);\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides\n ): Promise<void> {\n const credentials = await awsCredentialsProvider.getCredentials();\n for (const region of regions) {\n await this.getRegionalUtilization(credentials, region);", "score": 33.75973328819838 }, { "filename": "src/service-utilizations/aws-ec2-instance-utilization.ts", "retrieved_chunk": " metricName, \n [{ Name: 'InstanceId', Value: instanceId }]);\n });\n }\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEc2InstanceUtilizationOverrides\n ) {\n const credentials = await awsCredentialsProvider.getCredentials();\n this.accountId = await getAccountId(credentials);", "score": 31.401938378525024 }, { "filename": "src/service-utilizations/ebs-volumes-utilization.tsx", "retrieved_chunk": " credentials, \n region, \n volumeId,\n 'AWS/EBS', \n metricName, \n [{ Name: 'VolumeId', Value: volumeId }]);\n });\n };\n await rateLimitMap(volumes, 5, 5, analyzeEbsVolume);\n }", "score": 26.908666259297842 }, { "filename": "src/service-utilizations/aws-nat-gateway-utilization.ts", "retrieved_chunk": " credentials, \n region, \n natGatewayArn,\n 'AWS/NATGateway', \n metricName, \n [{ Name: 'NatGatewayId', Value: natGatewayId }]);\n });\n };\n await rateLimitMap(allNatGateways, 5, 5, analyzeNatGateway);\n }", "score": 26.908666259297842 }, { "filename": "src/service-utilizations/aws-ecs-utilization.ts", "retrieved_chunk": " {\n Name: 'ClusterName',\n Value: service.clusterArn?.split('/').pop()\n }]);\n });\n }\n console.info('this.utilization:\\n', JSON.stringify(this.utilization, null, 2));\n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsEcsUtilizationOverrides", "score": 23.76892133713675 } ]
typescript
awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides ) {
import React from 'react'; import { Box, Heading, Text, SimpleGrid } from '@chakra-ui/react'; import { ActionType, HistoryEvent, Utilization } from '../types/types.js'; import { filterUtilizationForActionType, getNumberOfResourcesFromFilteredActions, getTotalMonthlySavings, getTotalNumberOfResources } from '../utils/utilization.js'; export default function RecommendationOverview ( props: { utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[] } ) { const { utilizations, sessionHistory } = props; const { totalUnusedResources, totalMonthlySavings, totalResources } = getTotalRecommendationValues(utilizations, sessionHistory); const labelStyles = { fontFamily: 'Inter', fontSize: '42px', fontWeight: '400', lineHeight: '150%', color: '#000000' }; const textStyles = { fontFamily: 'Inter', fontSize: '14px', fontWeight: '500', lineHeight: '150%', color: 'rgba(0, 0, 0, 0.48)' }; return ( <SimpleGrid columns={3} spacing={2}> <Box p={5}> <Heading style={labelStyles}>{totalResources}</Heading> <Text style={textStyles}>{'resources'}</Text> </Box> <Box p={5}> <Heading style={labelStyles}>{totalUnusedResources}</Heading> <Text style={textStyles}>{'unused resources'}</Text> </Box> <Box p={5}> <Heading style={labelStyles}>{ totalMonthlySavings }</Heading> <Text style={textStyles}>{'potential monthly savings'}</Text> </Box> </SimpleGrid> ); } function getTotalRecommendationValues ( utilizations: { [ serviceName: string ] : Utilization<string> }, sessionHistory: HistoryEvent[] ) {
const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);
const totalUnusedResources = getNumberOfResourcesFromFilteredActions(deleteChanges); const totalResources = getTotalNumberOfResources(utilizations); const totalMonthlySavings = getTotalMonthlySavings(utilizations); return { totalUnusedResources, totalMonthlySavings, totalResources }; }
src/components/recommendation-overview.tsx
tinystacks-ops-aws-utilization-widgets-2ef7122
[ { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": "import { ActionType } from '../../types/types.js';\nimport { RecommendationsActionSummaryProps } from '../../types/utilization-recommendations-types.js';\nimport { TbRefresh } from 'react-icons/tb/index.js';\nexport function RecommendationsActionSummary (props: RecommendationsActionSummaryProps) {\n const { utilization, sessionHistory, onContinue, onRefresh, allRegions, region: regionLabel, onRegionChange } = props;\n const deleteChanges = filterUtilizationForActionType(utilization, ActionType.DELETE, sessionHistory);\n const scaleDownChanges = filterUtilizationForActionType(utilization, ActionType.SCALE_DOWN, sessionHistory);\n const optimizeChanges = filterUtilizationForActionType(utilization, ActionType.OPTIMIZE, sessionHistory);\n const numDeleteChanges = getNumberOfResourcesFromFilteredActions(deleteChanges);\n const numScaleDownChanges = getNumberOfResourcesFromFilteredActions(scaleDownChanges);", "score": 28.456879401084414 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-action-summary.tsx", "retrieved_chunk": " {icon}\n </Box>\n <Stack w='450px' pl='1'>\n <Box>\n <Heading as='h5' size='sm'>{actionLabel}</Heading>\n </Box>\n <Box>\n <Text fontSize='sm' color='gray.500'>{description}</Text>\n </Box>\n </Stack>", "score": 27.748830004787717 }, { "filename": "src/utils/utilization.ts", "retrieved_chunk": "import isEmpty from 'lodash.isempty';\nimport { ActionType, HistoryEvent, Scenarios, Utilization } from '../types/types.js';\nexport function filterUtilizationForActionType (\n utilization: { [service: string]: Utilization<string> }, actionType: ActionType, session: HistoryEvent[]\n):\n{ [service: string]: Utilization<string> } {\n const filtered: { [service: string]: Utilization<string> } = {};\n if (!utilization) {\n return filtered;\n }", "score": 21.96859260738869 }, { "filename": "src/widgets/utilization-recommendations-ui/recommendations-table.tsx", "retrieved_chunk": "export function RecommendationsTable (props: RecommendationsTableProps) {\n const { utilization, actionType, onRefresh, sessionHistory } = props;\n const [checkedResources, setCheckedResources] = useState<string[]>([]);\n const [checkedServices, setCheckedServices] = useState<string[]>([]);\n const [showSideModal, setShowSideModal] = useState<boolean | undefined>(undefined);\n const [ sidePanelResourceArn, setSidePanelResourceArn ] = useState<string | undefined>(undefined);\n const [ sidePanelService, setSidePanelService ] = useState<string | undefined>(undefined);\n const filteredServices = filterUtilizationForActionType(utilization, actionType, sessionHistory);\n const usd = new Intl.NumberFormat('en-US', {\n style: 'currency',", "score": 21.374603768936684 }, { "filename": "src/types/utilization-recommendations-types.ts", "retrieved_chunk": "import { Widget } from '@tinystacks/ops-model';\nimport { ActionType, AwsResourceType, HistoryEvent, Utilization } from './types.js';\nexport type HasActionType = {\n actionType: ActionType;\n}\nexport type HasUtilization = {\n utilization: { [key: AwsResourceType | string]: Utilization<string> };\n sessionHistory: HistoryEvent[];\n}\ninterface RemovableResource {", "score": 21.338056615134033 } ]
typescript
const deleteChanges = filterUtilizationForActionType(utilizations, ActionType.DELETE, sessionHistory);
/* * @vinejs/vine * * (c) VineJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import normalizeEmail from 'validator/lib/normalizeEmail.js' import escape from 'validator/lib/escape.js' import type { FieldContext } from '@vinejs/compiler/types' import { helpers } from '../../vine/helpers.js' import { messages } from '../../defaults.js' import { createRule } from '../../vine/create_rule.js' import type { URLOptions, AlphaOptions, EmailOptions, MobileOptions, PassportOptions, CreditCardOptions, PostalCodeOptions, NormalizeUrlOptions, AlphaNumericOptions, NormalizeEmailOptions, } from '../../types.js' import camelcase from 'camelcase' import normalizeUrl from 'normalize-url' /** * Validates the value to be a string */ export const stringRule = createRule((value, _, field) => { if (typeof value !== 'string') { field.report(messages.string, 'string', field) } }) /** * Validates the value to be a valid email address */ export const emailRule = createRule<EmailOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isEmail(value as string, options)) { field.report(messages.email, 'email', field) } }) /** * Validates the value to be a valid mobile number */ export const mobileRule = createRule< MobileOptions | undefined | ((field: FieldContext) => MobileOptions | undefined) >((value, options, field) => { if (!field.isValid) { return } const normalizedOptions = options && typeof options === 'function' ? options(field) : options const locales = normalizedOptions?.locale || 'any' if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { field.report(messages.mobile, 'mobile', field) } }) /** * Validates the value to be a valid IP address. */ export const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isIP(value as string, options?.version)) { field.report(messages.ipAddress, 'ipAddress', field) } }) /** * Validates the value against a regular expression */ export const regexRule = createRule<RegExp>((value, expression, field) => { if (!field.isValid) { return } if (!expression.test(value as string)) { field.report(messages.regex, 'regex', field) } }) /** * Validates the value to be a valid hex color code */ export const hexCodeRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isHexColor(value as string)) { field.report(messages.hexCode, 'hexCode', field) } }) /** * Validates the value to be a valid URL */ export const urlRule = createRule<URLOptions | undefined>((value, options, field) => { if (!field.isValid) { return } if (!helpers.isURL(value as string, options)) { field.report(messages.url, 'url', field) } }) /** * Validates the value to be an active URL */ export const activeUrlRule = createRule(async (value, _, field) => { if (!field.isValid) { return } if (!(await helpers.isActiveURL(value as string))) { field.report(messages.activeUrl, 'activeUrl', field) } }) /** * Validates the value to contain only letters */ export const alphaRule = createRule<AlphaOptions | undefined>((value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alpha, 'alpha', field) } }) /** * Validates the value to contain only letters and numbers */ export const alphaNumericRule = createRule<AlphaNumericOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } let characterSet = 'a-zA-Z0-9' if (options) { if (options.allowSpaces) { characterSet += '\\s' } if (options.allowDashes) { characterSet += '-' } if (options.allowUnderscores) { characterSet += '_' } } const expression = new RegExp(`^[${characterSet}]+$`) if (!expression.test(value as string)) { field.report(messages.alphaNumeric, 'alphaNumeric', field) } } ) /** * Enforce a minimum length on a string field */ export const minLengthRule = createRule<{ min: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length < options.min) { field.report(messages.minLength, 'minLength', field, options) } }) /** * Enforce a maximum length on a string field */ export const maxLengthRule = createRule<{ max: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length > options.max) { field.report(messages.maxLength, 'maxLength', field, options) } }) /** * Enforce a fixed length on a string field */ export const fixedLengthRule = createRule<{ size: number }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if ((value as string).length !== options.size) { field.report(messages.fixedLength, 'fixedLength', field, options) } }) /** * Ensure the value ends with the pre-defined substring */ export const endsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).endsWith(options.substring)) { field.report(messages.endsWith, 'endsWith', field, options) } }) /** * Ensure the value starts with the pre-defined substring */ export const startsWithRule = createRule<{ substring: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } if (!(value as string).startsWith(options.substring)) { field.report(messages.startsWith, 'startsWith', field, options) } }) /** * Ensure the field's value under validation is the same as the other field's value */ export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input !== value) { field.report(messages.sameAs, 'sameAs', field, options) return } }) /** * Ensure the field's value under validation is different from another field's value */ export const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const input = field.parent[options.otherField] /** * Performing validation and reporting error */ if (input === value) { field.report(messages.notSameAs, 'notSameAs', field, options) return } }) /** * Ensure the field under validation is confirmed by * having another field with the same name */ export const confirmedRule = createRule<{ confirmationField: string } | undefined>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const otherField = options?.confirmationField || `${field.name}_confirmation` const input = field.parent[otherField] /** * Performing validation and reporting error */ if (input !== value) {
field.report(messages.confirmed, 'confirmed', field, { otherField }) return }
} ) /** * Trims whitespaces around the string value */ export const trimRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate((value as string).trim(), field) }) /** * Normalizes the email address */ export const normalizeEmailRule = createRule<NormalizeEmailOptions | undefined>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeEmail.default(value as string, options), field) } ) /** * Converts the field value to UPPERCASE. */ export const toUpperCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleUpperCase(locales), field) } ) /** * Converts the field value to lowercase. */ export const toLowerCaseRule = createRule<string | string[] | undefined>( (value, locales, field) => { if (!field.isValid) { return } field.mutate((value as string).toLocaleLowerCase(locales), field) } ) /** * Converts the field value to camelCase. */ export const toCamelCaseRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(camelcase(value as string), field) }) /** * Escape string for HTML entities */ export const escapeRule = createRule((value, _, field) => { if (!field.isValid) { return } field.mutate(escape.default(value as string), field) }) /** * Normalize a URL */ export const normalizeUrlRule = createRule<undefined | NormalizeUrlOptions>( (value, options, field) => { if (!field.isValid) { return } field.mutate(normalizeUrl(value as string, options), field) } ) /** * Ensure the field's value under validation is a subset of the pre-defined list. */ export const inRule = createRule<{ choices: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices /** * Performing validation and reporting error */ if (!choices.includes(value as string)) { field.report(messages.in, 'in', field, options) return } } ) /** * Ensure the field's value under validation is not inside the pre-defined list. */ export const notInRule = createRule<{ list: string[] | ((field: FieldContext) => string[]) }>( (value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const list = typeof options.list === 'function' ? options.list(field) : options.list /** * Performing validation and reporting error */ if (list.includes(value as string)) { field.report(messages.notIn, 'notIn', field, options) return } } ) /** * Validates the value to be a valid credit card number */ export const creditCardRule = createRule< CreditCardOptions | undefined | ((field: FieldContext) => CreditCardOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const providers = options ? typeof options === 'function' ? options(field)?.provider || [] : options.provider : [] if (!providers.length) { if (!helpers.isCreditCard(value as string)) { field.report(messages.creditCard, 'creditCard', field, { providersList: 'credit', }) } } else { const matchesAnyProvider = providers.find((provider) => helpers.isCreditCard(value as string, { provider }) ) if (!matchesAnyProvider) { field.report(messages.creditCard, 'creditCard', field, { providers: providers, providersList: providers.join('/'), }) } } }) /** * Validates the value to be a valid passport number */ export const passportRule = createRule< PassportOptions | ((field: FieldContext) => PassportOptions) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = typeof options === 'function' ? options(field).countryCode : options.countryCode const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPassportNumber(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.passport, 'passport', field, { countryCodes }) } }) /** * Validates the value to be a valid postal code */ export const postalCodeRule = createRule< PostalCodeOptions | undefined | ((field: FieldContext) => PostalCodeOptions | void | undefined) >((value, options, field) => { /** * Skip if the field is not valid. */ if (!field.isValid) { return } const countryCodes = options ? typeof options === 'function' ? options(field)?.countryCode || [] : options.countryCode : [] if (!countryCodes.length) { if (!helpers.isPostalCode(value as string, 'any')) { field.report(messages.postalCode, 'postalCode', field) } } else { const matchesAnyCountryCode = countryCodes.find((countryCode) => helpers.isPostalCode(value as string, countryCode) ) if (!matchesAnyCountryCode) { field.report(messages.postalCode, 'postalCode', field, { countryCodes }) } } }) /** * Validates the value to be a valid UUID */ export const uuidRule = createRule<{ version?: (1 | 2 | 3 | 4 | 5)[] } | undefined>( (value, options, field) => { if (!field.isValid) { return } if (!options || !options.version) { if (!helpers.isUUID(value as string)) { field.report(messages.uuid, 'uuid', field) } } else { const matchesAnyVersion = options.version.find((version) => helpers.isUUID(value as string, version) ) if (!matchesAnyVersion) { field.report(messages.uuid, 'uuid', field, options) } } } ) /** * Validates the value contains ASCII characters only */ export const asciiRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isAscii(value as string)) { field.report(messages.ascii, 'ascii', field) } }) /** * Validates the value to be a valid IBAN number */ export const ibanRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isIBAN(value as string)) { field.report(messages.iban, 'iban', field) } }) /** * Validates the value to be a valid JWT token */ export const jwtRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isJWT(value as string)) { field.report(messages.jwt, 'jwt', field) } }) /** * Ensure the value is a string with latitude and longitude coordinates */ export const coordinatesRule = createRule((value, _, field) => { if (!field.isValid) { return } if (!helpers.isLatLong(value as string)) { field.report(messages.coordinates, 'coordinates', field) } })
src/schema/string/rules.ts
vinejs-vine-f8fa0af
[ { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " */\n if (typeof options.expectedValue === 'boolean') {\n input = helpers.asBoolean(value)\n } else if (typeof options.expectedValue === 'number') {\n input = helpers.asNumber(value)\n }\n /**\n * Performing validation and reporting error\n */\n if (input !== options.expectedValue) {", "score": 34.76830836977544 }, { "filename": "src/defaults.ts", "retrieved_chunk": " 'fixedLength': 'The {{ field }} field must be {{ size }} characters long',\n 'confirmed': 'The {{ field }} field and {{ otherField }} field must be the same',\n 'endsWith': 'The {{ field }} field must end with {{ substring }}',\n 'startsWith': 'The {{ field }} field must start with {{ substring }}',\n 'sameAs': 'The {{ field }} field and {{ otherField }} field must be the same',\n 'notSameAs': 'The {{ field }} field and {{ otherField }} field must be different',\n 'in': 'The selected {{ field }} is invalid',\n 'notIn': 'The selected {{ field }} is invalid',\n 'ipAddress': 'The {{ field }} field must be a valid IP address',\n 'uuid': 'The {{ field }} field must be a valid UUID',", "score": 32.32840298670786 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " fixedLength(expectedLength: number) {\n return this.use(fixedLengthRule({ size: expectedLength }))\n }\n /**\n * Ensure the field under validation is confirmed by\n * having another field with the same name.\n */\n confirmed(options?: { confirmationField: string }) {\n return this.use(confirmedRule(options))\n }", "score": 32.23276602902453 }, { "filename": "src/schema/literal/rules.ts", "retrieved_chunk": " field.report(messages.literal, 'literal', field, options)\n return\n }\n /**\n * Mutating input with normalized value\n */\n field.mutate(input, field)\n})", "score": 28.9468692501274 }, { "filename": "src/schema/string/main.ts", "retrieved_chunk": " /**\n * Ensure the value ends with the pre-defined substring\n */\n notSameAs(otherField: string) {\n return this.use(notSameAsRule({ otherField }))\n }\n /**\n * Ensure the field's value under validation is a subset of the pre-defined list.\n */\n in(choices: string[] | ((field: FieldContext) => string[])) {", "score": 28.09414544784658 } ]
typescript
field.report(messages.confirmed, 'confirmed', field, { otherField }) return }