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": 0.8902470469474792
},
{
"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": 0.8887749910354614
},
{
"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": 0.855766236782074
},
{
"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": 0.8425979614257812
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\nimport { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js'\n/**\n * VineRecord represents an object of key-value pair in which\n * keys are unknown\n */\nexport class VineRecord<Schema extends SchemaTypes> extends BaseType<\n { [K: string]: Schema[typeof OTYPE] },",
"score": 0.8397667407989502
}
] | 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/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": 0.9164097309112549
},
{
"filename": "src/vine/validator.ts",
"retrieved_chunk": " errorReporter: () => ErrorReporterContract\n /**\n * Parses schema to compiler nodes.\n */\n #parse(schema: Schema) {\n const refs = refsBuilder()\n return {\n compilerNode: {\n type: 'root' as const,\n schema: schema[PARSE]('', refs, { toCamelCase: false }),",
"score": 0.9159846305847168
},
{
"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": 0.9147838354110718
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.9123517274856567
},
{
"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": 0.9104427099227905
}
] | 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/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": 0.8605750799179077
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.8537250757217407
},
{
"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": 0.84893399477005
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema) {\n super()\n this.#schema = schema\n }\n /**\n * Clone object\n */",
"score": 0.8450567722320557
},
{
"filename": "src/vine/helpers.ts",
"retrieved_chunk": " * }\n * ], ['email', 'tenant_id']) // true\n * ```\n */\n isDistinct: (dataSet: any[], fields?: string | string[]): boolean => {\n const uniqueItems: Set<any> = new Set()\n /**\n * Check for duplicates when no fields are provided\n */\n if (!fields) {",
"score": 0.841476559638977
}
] | typescript | !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 { 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": 0.917548418045044
},
{
"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": 0.9112414121627808
},
{
"filename": "src/schema/number/main.ts",
"retrieved_chunk": " return !Number.isNaN(valueAsNumber)\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {\n super(options, validations || [numberRule(options || {})])\n }\n /**\n * Enforce a minimum value for the number input",
"score": 0.9012278318405151
},
{
"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": 0.8998265862464905
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.8956712484359741
}
] | 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": 0.8876137137413025
},
{
"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": 0.8607273101806641
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " group: Group\n ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {\n this.#groups.push(group)\n return this as VineObject<\n Properties,\n Output & Group[typeof OTYPE],\n CamelCaseOutput & Group[typeof COTYPE]\n >\n }\n /**",
"score": 0.8340046405792236
},
{
"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": 0.8219431638717651
},
{
"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": 0.8188982009887695
}
] | 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": 0.9061410427093506
},
{
"filename": "src/schema/number/main.ts",
"retrieved_chunk": " return !Number.isNaN(valueAsNumber)\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {\n super(options, validations || [numberRule(options || {})])\n }\n /**\n * Enforce a minimum value for the number input",
"score": 0.8988885283470154
},
{
"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": 0.8978712558746338
},
{
"filename": "src/schema/array/main.ts",
"retrieved_chunk": " return Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an array field\n */\n minLength(expectedLength: number) {",
"score": 0.8891910910606384
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#properties = properties\n }\n /**\n * Returns a clone copy of the object properties. The object groups\n * are not copied to keep the implementations simple and easy to",
"score": 0.8866510987281799
}
] | 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 { 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": 0.9075626134872437
},
{
"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": 0.9007582664489746
},
{
"filename": "src/schema/number/main.ts",
"retrieved_chunk": " return !Number.isNaN(valueAsNumber)\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {\n super(options, validations || [numberRule(options || {})])\n }\n /**\n * Enforce a minimum value for the number input",
"score": 0.8994062542915344
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#properties = properties\n }\n /**\n * Returns a clone copy of the object properties. The object groups\n * are not copied to keep the implementations simple and easy to",
"score": 0.8903056979179382
},
{
"filename": "src/schema/array/main.ts",
"retrieved_chunk": " return Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an array field\n */\n minLength(expectedLength: number) {",
"score": 0.8859164118766785
}
] | 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": 0.9192277789115906
},
{
"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": 0.8975576162338257
},
{
"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": 0.8915969133377075
},
{
"filename": "src/vine/main.ts",
"retrieved_chunk": " errorReporter: this.errorReporter,\n })\n }\n /**\n * Define a callback to validate the metadata given to the validator\n * at runtime\n */\n withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator) {\n return {\n compile: <Schema extends SchemaTypes>(schema: Schema) => {",
"score": 0.8903586864471436
},
{
"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": 0.8897155523300171
}
] | 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 { 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/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": 0.918213427066803
},
{
"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": 0.8961989879608154
},
{
"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": 0.8739746809005737
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.8732869625091553
},
{
"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": 0.8729132413864136
}
] | 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 { 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": 0.8834693431854248
},
{
"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": 0.8451273441314697
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " group: Group\n ): VineObject<Properties, Output & Group[typeof OTYPE], CamelCaseOutput & Group[typeof COTYPE]> {\n this.#groups.push(group)\n return this as VineObject<\n Properties,\n Output & Group[typeof OTYPE],\n CamelCaseOutput & Group[typeof COTYPE]\n >\n }\n /**",
"score": 0.8288331031799316
},
{
"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": 0.8269097208976746
},
{
"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": 0.8245784044265747
}
] | 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 { 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": " }\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": 0.915571391582489
},
{
"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": 0.8970068693161011
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " return\n }\n if (!helpers.isURL(value as string, options)) {\n field.report(messages.url, 'url', field)\n }\n})\n/**\n * Validates the value to be an active URL\n */\nexport const activeUrlRule = createRule(async (value, _, field) => {",
"score": 0.8928147554397583
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " */\nexport const stringRule = createRule((value, _, field) => {\n if (typeof value !== 'string') {\n field.report(messages.string, 'string', field)\n }\n})\n/**\n * Validates the value to be a valid email address\n */\nexport const emailRule = createRule<EmailOptions | undefined>((value, options, field) => {",
"score": 0.8897043466567993
},
{
"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": 0.8879419565200806
}
] | 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 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": 0.9156215190887451
},
{
"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": 0.8975917100906372
},
{
"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": 0.8965897560119629
},
{
"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": 0.8637739419937134
},
{
"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": 0.8618039488792419
}
] | 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/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": 0.9142969846725464
},
{
"filename": "src/vine/validator.ts",
"retrieved_chunk": " errorReporter: () => ErrorReporterContract\n /**\n * Parses schema to compiler nodes.\n */\n #parse(schema: Schema) {\n const refs = refsBuilder()\n return {\n compilerNode: {\n type: 'root' as const,\n schema: schema[PARSE]('', refs, { toCamelCase: false }),",
"score": 0.9136854410171509
},
{
"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": 0.9104353785514832
},
{
"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": 0.9077656865119934
},
{
"filename": "src/schema/base/literal.ts",
"retrieved_chunk": " /**\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\n */",
"score": 0.9051786661148071
}
] | 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": " * 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": 0.9294717311859131
},
{
"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": 0.9215730428695679
},
{
"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": 0.9064882397651672
},
{
"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": 0.9059658050537109
},
{
"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": 0.8996133208274841
}
] | 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/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": 0.9089611172676086
},
{
"filename": "src/types.ts",
"retrieved_chunk": " */\nexport type ValidationMessages = Record<string, string>\nexport type ValidationFields = Record<string, string>\n/**\n * Constructable schema type refers to any type that can be\n * constructed for type inference and compiler output\n */\nexport interface ConstructableSchema<Output, CamelCaseOutput> {\n [OTYPE]: Output\n [COTYPE]: CamelCaseOutput",
"score": 0.9078025817871094
},
{
"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": 0.8997421264648438
},
{
"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": 0.8832634687423706
},
{
"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": 0.8742111921310425
}
] | 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": 0.9627015590667725
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9499465823173523
},
{
"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": 0.947730541229248
},
{
"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": 0.9286971092224121
},
{
"filename": "src/schema/boolean/main.ts",
"retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {",
"score": 0.9279404282569885
}
] | 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": 0.9697771072387695
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9473503828048706
},
{
"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": 0.9453895092010498
},
{
"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": 0.9293431639671326
},
{
"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": 0.9220130443572998
}
] | 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/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": 0.8751599192619324
},
{
"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": 0.8685604333877563
},
{
"filename": "src/schema/union/builder.ts",
"retrieved_chunk": "import type { FieldContext, SchemaTypes } from '../../types.js'\n/**\n * Create a new union schema type. A union is a collection of conditionals\n * and schema associated with it.\n */\nexport function union<Conditional extends UnionConditional<any>>(conditionals: Conditional[]) {\n return new VineUnion<Conditional>(conditionals)\n}\n/**\n * Wrap object properties inside a conditonal",
"score": 0.8618176579475403
},
{
"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": 0.8581870794296265
},
{
"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": 0.8564056754112244
}
] | 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/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": 0.87835294008255
},
{
"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": 0.8729327321052551
},
{
"filename": "src/schema/union/builder.ts",
"retrieved_chunk": "import type { FieldContext, SchemaTypes } from '../../types.js'\n/**\n * Create a new union schema type. A union is a collection of conditionals\n * and schema associated with it.\n */\nexport function union<Conditional extends UnionConditional<any>>(conditionals: Conditional[]) {\n return new VineUnion<Conditional>(conditionals)\n}\n/**\n * Wrap object properties inside a conditonal",
"score": 0.8684903979301453
},
{
"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": 0.8655885457992554
},
{
"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": 0.8632800579071045
}
] | 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": 0.9169667959213257
},
{
"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": 0.7939183712005615
},
{
"filename": "src/schema/accepted/main.ts",
"retrieved_chunk": " }\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super(options, validations || [acceptedRule()])\n }\n /**\n * Clones the VineAccepted schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineAccepted(this.cloneOptions(), this.cloneValidations()) as this",
"score": 0.7896455526351929
},
{
"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": 0.7892628908157349
},
{
"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": 0.7843450307846069
}
] | 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/boolean/main.ts",
"retrieved_chunk": " static rules = {\n boolean: booleanRule,\n }\n protected declare options: FieldOptions & { strict?: boolean };\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.boolean';\n /**\n * Checks if the value is of boolean type. The method must be",
"score": 0.8872512578964233
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " { [K: string]: Schema[typeof COTYPE] }\n> {\n /**\n * Default collection of record rules\n */\n static rules = {\n maxLength: maxLengthRule,\n minLength: minLengthRule,\n fixedLength: fixedLengthRule,\n validateKeys: validateKeysRule,",
"score": 0.8785583972930908
},
{
"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": 0.8688617944717407
},
{
"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": 0.867940366268158
},
{
"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": 0.8656604290008545
}
] | 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": 0.9175431728363037
},
{
"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": 0.9124349355697632
},
{
"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": 0.9096477031707764
},
{
"filename": "src/schema/accepted/main.ts",
"retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineAccepted represents a checkbox input that must be checked\n */\nexport class VineAccepted extends BaseLiteralType<true, true> {\n /**\n * Default collection of accepted rules\n */\n static rules = {\n accepted: acceptedRule,",
"score": 0.8973315954208374
},
{
"filename": "src/schema/enum/main.ts",
"retrieved_chunk": "import type { FieldContext, FieldOptions, Validation } from '../../types.js'\n/**\n * VineEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n */\nexport class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType<\n Values[number],\n Values[number]\n> {\n /**",
"score": 0.881427526473999
}
] | typescript | VineString extends BaseLiteralType<string, string> { |
/*
* 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": 0.9117484092712402
},
{
"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": 0.9007267951965332
},
{
"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": 0.8479269742965698
},
{
"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": 0.8270431756973267
},
{
"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": 0.8164485096931458
}
] | typescript | 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/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": 0.8783355951309204
},
{
"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": 0.8746705055236816
},
{
"filename": "src/schema/union/builder.ts",
"retrieved_chunk": "import type { FieldContext, SchemaTypes } from '../../types.js'\n/**\n * Create a new union schema type. A union is a collection of conditionals\n * and schema associated with it.\n */\nexport function union<Conditional extends UnionConditional<any>>(conditionals: Conditional[]) {\n return new VineUnion<Conditional>(conditionals)\n}\n/**\n * Wrap object properties inside a conditonal",
"score": 0.8674402236938477
},
{
"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": 0.8633012771606445
},
{
"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": 0.8610464334487915
}
] | typescript | Output & Group[typeof OTYPE], CamelCaseOutput & Group[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 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": 0.938581109046936
},
{
"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": 0.9284497499465942
},
{
"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": 0.9259158372879028
},
{
"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": 0.920592725276947
},
{
"filename": "src/schema/string/main.ts",
"retrieved_chunk": " * numbers\n */\n alphaNumeric(options?: AlphaNumericOptions) {\n return this.use(alphaNumericRule(options))\n }\n /**\n * Enforce a minimum length on a string field\n */\n minLength(expectedLength: number) {\n return this.use(minLengthRule({ min: expectedLength }))",
"score": 0.9045767784118652
}
] | typescript | (...args: Parameters<typeof validateKeysRule>) { |
/*
* @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": 0.8806995749473572
},
{
"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": 0.8691694736480713
},
{
"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": 0.865413248538971
},
{
"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": 0.8650832176208496
},
{
"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": 0.8614182472229004
}
] | 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": 0.9297029376029968
},
{
"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": 0.9127565622329712
},
{
"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": 0.9093016386032104
},
{
"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": 0.9049393534660339
},
{
"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": 0.9029030203819275
}
] | 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/number/main.ts",
"retrieved_chunk": " return !Number.isNaN(valueAsNumber)\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {\n super(options, validations || [numberRule(options || {})])\n }\n /**\n * Enforce a minimum value for the number input",
"score": 0.9250819683074951
},
{
"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": 0.9182911515235901
},
{
"filename": "src/schema/array/main.ts",
"retrieved_chunk": " return Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an array field\n */\n minLength(expectedLength: number) {",
"score": 0.9109677672386169
},
{
"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": 0.9101625084877014
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9077345728874207
}
] | 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/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": 0.794937014579773
},
{
"filename": "src/schema/string/main.ts",
"retrieved_chunk": " return this.use(inRule({ choices }))\n }\n /**\n * Ensure the field's value under validation is not inside the pre-defined list.\n */\n notIn(list: string[] | ((field: FieldContext) => string[])) {\n return this.use(notInRule({ list }))\n }\n /**\n * Validates the value to be a valid credit card number",
"score": 0.7909680008888245
},
{
"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": 0.7881763577461243
},
{
"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": 0.7844388484954834
},
{
"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": 0.7842534780502319
}
] | 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 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": 0.9232439994812012
},
{
"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": 0.9112610816955566
},
{
"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": 0.90784752368927
},
{
"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": 0.9073125123977661
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.899588942527771
}
] | 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 { 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": " */\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": 0.9132155776023865
},
{
"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": 0.9002866148948669
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {",
"score": 0.8796127438545227
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " */\n if (input !== value) {\n field.report(messages.sameAs, 'sameAs', field, options)\n return\n }\n})\n/**\n * Ensure the field's value under validation is different from another field's value\n */\nexport const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => {",
"score": 0.8729302883148193
},
{
"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": 0.8596212863922119
}
] | 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/number/rules.ts",
"retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {",
"score": 0.8844537734985352
},
{
"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": 0.8776024580001831
},
{
"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": 0.8741798400878906
},
{
"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": 0.8691114187240601
},
{
"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": 0.8689272403717041
}
] | 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/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": 0.8489967584609985
},
{
"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": 0.8385077118873596
},
{
"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": 0.8382192254066467
},
{
"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": 0.8238463401794434
},
{
"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": 0.8232876062393188
}
] | 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": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {",
"score": 0.9214283227920532
},
{
"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": 0.9204176068305969
},
{
"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": 0.9199225902557373
},
{
"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": 0.9198950529098511
},
{
"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": 0.9184461832046509
}
] | 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 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": 0.9170882105827332
},
{
"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": 0.9149366617202759
},
{
"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": 0.9001150131225586
},
{
"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": 0.8969714045524597
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {",
"score": 0.8963803052902222
}
] | 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/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": 0.8999043703079224
},
{
"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": 0.8983574509620667
},
{
"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": 0.8910921812057495
},
{
"filename": "src/schema/accepted/main.ts",
"retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineAccepted represents a checkbox input that must be checked\n */\nexport class VineAccepted extends BaseLiteralType<true, true> {\n /**\n * Default collection of accepted rules\n */\n static rules = {\n accepted: acceptedRule,",
"score": 0.8781395554542542
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { OTYPE, COTYPE, PARSE, UNIQUE_NAME, IS_OF_TYPE } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\nimport { fixedLengthRule, maxLengthRule, minLengthRule, validateKeysRule } from './rules.js'\n/**\n * VineRecord represents an object of key-value pair in which\n * keys are unknown\n */\nexport class VineRecord<Schema extends SchemaTypes> extends BaseType<\n { [K: string]: Schema[typeof OTYPE] },",
"score": 0.8683127760887146
}
] | 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/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": 0.9399085640907288
},
{
"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": 0.9398252367973328
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9370043277740479
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#properties = properties\n }\n /**\n * Returns a clone copy of the object properties. The object groups\n * are not copied to keep the implementations simple and easy to",
"score": 0.927787184715271
},
{
"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": 0.9244924783706665
}
] | 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/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": 0.9276766180992126
},
{
"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": 0.9263037443161011
},
{
"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": 0.922287106513977
},
{
"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": 0.9075775742530823
},
{
"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": 0.8990341424942017
}
] | 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/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": 0.9381504058837891
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9327771067619324
},
{
"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": 0.9291671514511108
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#properties = properties\n }\n /**\n * Returns a clone copy of the object properties. The object groups\n * are not copied to keep the implementations simple and easy to",
"score": 0.9203454852104187
},
{
"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": 0.9194124937057495
}
] | 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/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": 0.934497594833374
},
{
"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": 0.9341054558753967
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9285430908203125
},
{
"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": 0.9232386946678162
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#properties = properties\n }\n /**\n * Returns a clone copy of the object properties. The object groups\n * are not copied to keep the implementations simple and easy to",
"score": 0.9194374084472656
}
] | 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 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": " field.report(messages.creditCard, 'creditCard', field, {\n providersList: 'credit',\n })\n }\n } else {\n const matchesAnyProvider = providers.find((provider) =>\n helpers.isCreditCard(value as string, { provider })\n )\n if (!matchesAnyProvider) {\n field.report(messages.creditCard, 'creditCard', field, {",
"score": 0.7049303650856018
},
{
"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": 0.699679970741272
},
{
"filename": "src/vine/helpers.ts",
"retrieved_chunk": " isCreditCard: isCreditCard.default,\n isIBAN: isIBAN.default,\n isJWT: isJWT.default,\n isLatLong: isLatLong.default,\n isMobilePhone: isMobilePhone.default,\n isPassportNumber: isPassportNumber.default,\n isPostalCode: isPostalCode.default,\n isSlug: isSlug.default,\n isDecimal: isDecimal.default,\n mobileLocales: mobilePhoneLocales as MobilePhoneLocale[],",
"score": 0.698832631111145
},
{
"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": 0.6982641816139221
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " providers: providers,\n providersList: providers.join('/'),\n })\n }\n }\n})\n/**\n * Validates the value to be a valid passport number\n */\nexport const passportRule = createRule<",
"score": 0.6852246522903442
}
] | 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 { 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": 0.919113278388977
},
{
"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": 0.8930788040161133
},
{
"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": 0.8901855945587158
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.8881585001945496
},
{
"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": 0.8876338601112366
}
] | 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 { 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/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.8949763178825378
},
{
"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": 0.889384388923645
},
{
"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": 0.8889234066009521
},
{
"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": 0.8866210579872131
},
{
"filename": "src/schema/base/literal.ts",
"retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\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.",
"score": 0.8827833533287048
}
] | 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/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": 0.9065210223197937
},
{
"filename": "src/schema/base/literal.ts",
"retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\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.",
"score": 0.8985627293586731
},
{
"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": 0.8922709226608276
},
{
"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": 0.889354944229126
},
{
"filename": "src/schema/tuple/main.ts",
"retrieved_chunk": " CamelCaseOutput extends any[],\n> extends BaseType<Output, CamelCaseOutput> {\n #schemas: [...Schema]\n /**\n * Whether or not to allow unknown properties\n */\n #allowUnknownProperties: boolean = false;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */",
"score": 0.8879525661468506
}
] | 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 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": 0.8662043809890747
},
{
"filename": "src/schema/object/conditional.ts",
"retrieved_chunk": " type: 'sub_object',\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: [], // Compiler allows nested groups, but we are not implementing it\n },\n conditionalFnRefId: refs.trackConditional(this.#conditional),\n }\n }\n}",
"score": 0.852835476398468
},
{
"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": 0.8339719772338867
},
{
"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": 0.8327652215957642
},
{
"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": 0.8291101455688477
}
] | 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 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": " field.report(messages.creditCard, 'creditCard', field, {\n providersList: 'credit',\n })\n }\n } else {\n const matchesAnyProvider = providers.find((provider) =>\n helpers.isCreditCard(value as string, { provider })\n )\n if (!matchesAnyProvider) {\n field.report(messages.creditCard, 'creditCard', field, {",
"score": 0.7072804570198059
},
{
"filename": "src/vine/helpers.ts",
"retrieved_chunk": " isCreditCard: isCreditCard.default,\n isIBAN: isIBAN.default,\n isJWT: isJWT.default,\n isLatLong: isLatLong.default,\n isMobilePhone: isMobilePhone.default,\n isPassportNumber: isPassportNumber.default,\n isPostalCode: isPostalCode.default,\n isSlug: isSlug.default,\n isDecimal: isDecimal.default,\n mobileLocales: mobilePhoneLocales as MobilePhoneLocale[],",
"score": 0.7038958072662354
},
{
"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": 0.7030980587005615
},
{
"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": 0.6985864639282227
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " providers: providers,\n providersList: providers.join('/'),\n })\n }\n }\n})\n/**\n * Validates the value to be a valid passport number\n */\nexport const passportRule = createRule<",
"score": 0.6855398416519165
}
] | 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/reporters/simple_error_reporter.ts",
"retrieved_chunk": "import type { ErrorReporterContract, FieldContext } from '../types.js'\n/**\n * Shape of the error message collected by the SimpleErrorReporter\n */\ntype SimpleError = {\n message: string\n field: string\n rule: string\n index?: number\n meta?: Record<string, any>",
"score": 0.8711540699005127
},
{
"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": 0.86341392993927
},
{
"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": 0.863225519657135
},
{
"filename": "src/schema/enum/main.ts",
"retrieved_chunk": "import type { FieldContext, FieldOptions, Validation } from '../../types.js'\n/**\n * VineEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n */\nexport class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType<\n Values[number],\n Values[number]\n> {\n /**",
"score": 0.8591008186340332
},
{
"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": 0.8589214086532593
}
] | 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": 0.9065210223197937
},
{
"filename": "src/schema/base/literal.ts",
"retrieved_chunk": " * one of the known compiler nodes\n */\n abstract [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): LiteralNode\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.",
"score": 0.8985627293586731
},
{
"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": 0.8922709226608276
},
{
"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": 0.889354944229126
},
{
"filename": "src/schema/tuple/main.ts",
"retrieved_chunk": " CamelCaseOutput extends any[],\n> extends BaseType<Output, CamelCaseOutput> {\n #schemas: [...Schema]\n /**\n * Whether or not to allow unknown properties\n */\n #allowUnknownProperties: boolean = false;\n /**\n * The property must be implemented for \"unionOfTypes\"\n */",
"score": 0.8879525661468506
}
] | 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": 0.9079954624176025
},
{
"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": 0.887237548828125
},
{
"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": 0.882903516292572
},
{
"filename": "src/vine/main.ts",
"retrieved_chunk": " errorReporter: this.errorReporter,\n })\n }\n /**\n * Define a callback to validate the metadata given to the validator\n * at runtime\n */\n withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator) {\n return {\n compile: <Schema extends SchemaTypes>(schema: Schema) => {",
"score": 0.8797663450241089
},
{
"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": 0.8775143027305603
}
] | 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 { 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/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": 0.8807962536811829
},
{
"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": 0.8784220218658447
},
{
"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": 0.8728150129318237
},
{
"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": 0.8632917404174805
},
{
"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": 0.8602991104125977
}
] | 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/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": 0.8850764036178589
},
{
"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": 0.867012619972229
},
{
"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": 0.8664817214012146
},
{
"filename": "src/schema/accepted/main.ts",
"retrieved_chunk": "import type { FieldOptions, Validation } from '../../types.js'\n/**\n * VineAccepted represents a checkbox input that must be checked\n */\nexport class VineAccepted extends BaseLiteralType<true, true> {\n /**\n * Default collection of accepted rules\n */\n static rules = {\n accepted: acceptedRule,",
"score": 0.8646907806396484
},
{
"filename": "src/schema/boolean/main.ts",
"retrieved_chunk": " static rules = {\n boolean: booleanRule,\n }\n protected declare options: FieldOptions & { strict?: boolean };\n /**\n * The property must be implemented for \"unionOfTypes\"\n */\n [UNIQUE_NAME] = 'vine.boolean';\n /**\n * Checks if the value is of boolean type. The method must be",
"score": 0.8635424375534058
}
] | 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 { 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": 0.886073112487793
},
{
"filename": "src/schema/builder.ts",
"retrieved_chunk": " */\n number(options?: { strict: boolean }) {\n return new VineNumber(options)\n }\n /**\n * Define a schema type in which the input value\n * matches the pre-defined value\n */\n literal<const Value>(value: Value) {\n return new VineLiteral<Value>(value)",
"score": 0.881264328956604
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface ErrorReporterContract extends BaseReporter {\n createError(): ValidationError\n}\n/**\n * The validator function to validate metadata given to a validation\n * pipeline\n */\nexport type MetaDataValidator = (meta: Record<string, any>) => void\n/**\n * Options accepted during the validate call.",
"score": 0.8800923824310303
},
{
"filename": "src/vine/validator.ts",
"retrieved_chunk": " errorReporter: () => ErrorReporterContract\n /**\n * Parses schema to compiler nodes.\n */\n #parse(schema: Schema) {\n const refs = refsBuilder()\n return {\n compilerNode: {\n type: 'root' as const,\n schema: schema[PARSE]('', refs, { toCamelCase: false }),",
"score": 0.8796181082725525
},
{
"filename": "src/schema/builder.ts",
"retrieved_chunk": " { [K in keyof Schema]: Schema[K][typeof COTYPE] }\n >(schemas)\n }\n /**\n * Define an object field with key-value pair. The keys in\n * a record are unknown and values can be of a specific\n * schema type.\n */\n record<Schema extends SchemaTypes>(schema: Schema) {\n return new VineRecord<Schema>(schema)",
"score": 0.8691935539245605
}
] | 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 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/reporters/simple_error_reporter.ts",
"retrieved_chunk": "import type { ErrorReporterContract, FieldContext } from '../types.js'\n/**\n * Shape of the error message collected by the SimpleErrorReporter\n */\ntype SimpleError = {\n message: string\n field: string\n rule: string\n index?: number\n meta?: Record<string, any>",
"score": 0.8843034505844116
},
{
"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": 0.8778277635574341
},
{
"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": 0.8761570453643799
},
{
"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": 0.8714593648910522
},
{
"filename": "src/schema/enum/main.ts",
"retrieved_chunk": "import type { FieldContext, FieldOptions, Validation } from '../../types.js'\n/**\n * VineEnum represents a enum data type that performs validation\n * against a pre-defined choices list.\n */\nexport class VineEnum<const Values extends readonly unknown[]> extends BaseLiteralType<\n Values[number],\n Values[number]\n> {\n /**",
"score": 0.8647409677505493
}
] | 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 { 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": 0.9236817955970764
},
{
"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": 0.9057837724685669
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " */\n if (!field.isValid) {\n return\n }\n if ((value as number) >= 0) {\n field.report(messages.negative, 'negative', field)\n }\n})\n/**\n * Enforce the value to have a fixed or range of decimals",
"score": 0.8936092853546143
},
{
"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": 0.8845062255859375
},
{
"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": 0.8816359043121338
}
] | 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 { 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/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": 0.8778940439224243
},
{
"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": 0.8758063316345215
},
{
"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": 0.8701056241989136
},
{
"filename": "src/schema/base/literal.ts",
"retrieved_chunk": " /**\n * Compiles validations\n */\n protected compileValidations(refs: RefsStore) {\n return this.validations.map((validation) => {\n return {\n ruleFnId: refs.track({\n validator: validation.rule.validator,\n options: validation.options,\n }),",
"score": 0.8581094741821289
},
{
"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": 0.8577722311019897
}
] | 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 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": 0.8645459413528442
},
{
"filename": "src/schema/object/conditional.ts",
"retrieved_chunk": " type: 'sub_object',\n properties: Object.keys(this.#properties).map((property) => {\n return this.#properties[property][PARSE](property, refs, options)\n }),\n groups: [], // Compiler allows nested groups, but we are not implementing it\n },\n conditionalFnRefId: refs.trackConditional(this.#conditional),\n }\n }\n}",
"score": 0.8481081128120422
},
{
"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": 0.83202064037323
},
{
"filename": "src/schema/base/literal.ts",
"retrieved_chunk": " /**\n * Compiles validations\n */\n protected compileValidations(refs: RefsStore) {\n return this.validations.map((validation) => {\n return {\n ruleFnId: refs.track({\n validator: validation.rule.validator,\n options: validation.options,\n }),",
"score": 0.8294756412506104
},
{
"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": 0.8288413286209106
}
] | 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/string/rules.ts",
"retrieved_chunk": " /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const input = field.parent[options.otherField]\n /**\n * Performing validation and reporting error\n */",
"score": 0.9215014576911926
},
{
"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": 0.9188441038131714
},
{
"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": 0.9165277481079102
},
{
"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": 0.9007521867752075
},
{
"filename": "src/schema/array/main.ts",
"retrieved_chunk": " /**\n * Ensure array elements are distinct/unique\n */\n distinct(fields?: string | string[]) {\n return this.use(distinctRule({ fields }))\n }\n /**\n * Removes empty strings, null and undefined values from the array\n */\n compact() {",
"score": 0.8987886905670166
}
] | 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": 0.9522017240524292
},
{
"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": 0.9385412931442261
},
{
"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": 0.9379874467849731
},
{
"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": 0.9184902906417847
},
{
"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": 0.9051336646080017
}
] | 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": 0.9308539628982544
},
{
"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": 0.9247534871101379
},
{
"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": 0.9206720590591431
},
{
"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": 0.906915545463562
},
{
"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": 0.8995976448059082
}
] | 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": 0.8909852504730225
},
{
"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": 0.8866734504699707
},
{
"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": 0.8749713897705078
},
{
"filename": "src/schema/literal/rules.ts",
"retrieved_chunk": "import { createRule } from '../../vine/create_rule.js'\n/**\n * Verifies two equals are equal considering the HTML forms\n * serialization behavior.\n */\nexport const equalsRule = createRule<{ expectedValue: any }>((value, options, field) => {\n let input = value\n /**\n * Normalizing the field value as per the expected\n * value.",
"score": 0.8701380491256714
},
{
"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": 0.8684259653091431
}
] | 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/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": 0.9050161242485046
},
{
"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": 0.8898000121116638
},
{
"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": 0.8893600702285767
},
{
"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": 0.8884248733520508
},
{
"filename": "src/vine/main.ts",
"retrieved_chunk": " errorReporter: this.errorReporter,\n })\n }\n /**\n * Define a callback to validate the metadata given to the validator\n * at runtime\n */\n withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator) {\n return {\n compile: <Schema extends SchemaTypes>(schema: Schema) => {",
"score": 0.8814584612846375
}
] | 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/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": 0.9079121947288513
},
{
"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": 0.898565948009491
},
{
"filename": "src/vine/main.ts",
"retrieved_chunk": " errorReporter: this.errorReporter,\n })\n }\n /**\n * Define a callback to validate the metadata given to the validator\n * at runtime\n */\n withMetaData<MetaData extends Record<string, any>>(callback?: MetaDataValidator) {\n return {\n compile: <Schema extends SchemaTypes>(schema: Schema) => {",
"score": 0.8661128282546997
},
{
"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": 0.8636962175369263
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.860617458820343
}
] | 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/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": 0.863932192325592
},
{
"filename": "src/schema/tuple/main.ts",
"retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\n/**\n * VineTuple is an array with known length and may have different\n * schema type for each array element.\n */\nexport class VineTuple<\n Schema extends SchemaTypes[],\n Output extends any[],",
"score": 0.8628783822059631
},
{
"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": 0.8626738786697388
},
{
"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": 0.8579663038253784
},
{
"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": 0.8520001769065857
}
] | 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 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/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": 0.8760321736335754
},
{
"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": 0.8701180219650269
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [PARSE](propertyName: string, refs: RefsStore, options: ParserOptions): CompilerNodes\n clone(): this\n /**\n * Implement if you want schema type to be used with the unionOfTypes\n */\n [UNIQUE_NAME]?: string\n [IS_OF_TYPE]?: (value: unknown, field: FieldContext) => boolean\n}\nexport type SchemaTypes = ConstructableSchema<any, any>\n/**",
"score": 0.8631460666656494
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema) {\n super()\n this.#schema = schema\n }\n /**\n * Clone object\n */",
"score": 0.8601559400558472
},
{
"filename": "src/vine/helpers.ts",
"retrieved_chunk": " * }\n * ], ['email', 'tenant_id']) // true\n * ```\n */\n isDistinct: (dataSet: any[], fields?: string | string[]): boolean => {\n const uniqueItems: Set<any> = new Set()\n /**\n * Check for duplicates when no fields are provided\n */\n if (!fields) {",
"score": 0.8588446974754333
}
] | 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 { 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": 0.9029865264892578
},
{
"filename": "src/schema/number/main.ts",
"retrieved_chunk": " return !Number.isNaN(valueAsNumber)\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {\n super(options, validations || [numberRule(options || {})])\n }\n /**\n * Enforce a minimum value for the number input",
"score": 0.8952293992042542
},
{
"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": 0.8942445516586304
},
{
"filename": "src/schema/array/main.ts",
"retrieved_chunk": " return Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an array field\n */\n minLength(expectedLength: number) {",
"score": 0.8859883546829224
},
{
"filename": "src/schema/object/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(properties: Properties, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#properties = properties\n }\n /**\n * Returns a clone copy of the object properties. The object groups\n * are not copied to keep the implementations simple and easy to",
"score": 0.8820026516914368
}
] | 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/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": 0.8709890246391296
},
{
"filename": "src/schema/tuple/main.ts",
"retrieved_chunk": "import { BaseType } from '../base/main.js'\nimport { IS_OF_TYPE, PARSE, UNIQUE_NAME } from '../../symbols.js'\nimport type { FieldOptions, ParserOptions, SchemaTypes, Validation } from '../../types.js'\n/**\n * VineTuple is an array with known length and may have different\n * schema type for each array element.\n */\nexport class VineTuple<\n Schema extends SchemaTypes[],\n Output extends any[],",
"score": 0.8690805435180664
},
{
"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": 0.8685086965560913
},
{
"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": 0.8678457140922546
},
{
"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": 0.8614468574523926
}
] | 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": 0.9828575253486633
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " * Ensure the value ends with the pre-defined substring\n */\nexport const endsWithRule = createRule<{ substring: string }>((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).endsWith(options.substring)) {",
"score": 0.9290037751197815
},
{
"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": 0.9285905361175537
},
{
"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": 0.9268957376480103
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": "export const sameAsRule = createRule<{ otherField: string }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {\n return\n }\n const input = field.parent[options.otherField]\n /**\n * Performing validation and reporting error",
"score": 0.9255197048187256
}
] | 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/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": 0.9080530405044556
},
{
"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": 0.907996654510498
},
{
"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": 0.9078832268714905
},
{
"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": 0.9025081396102905
},
{
"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": 0.8887544274330139
}
] | 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": 0.9189821481704712
},
{
"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": 0.9046945571899414
},
{
"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": 0.903244137763977
},
{
"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": 0.8703539967536926
},
{
"filename": "src/schema/object/group.ts",
"retrieved_chunk": " declare [COTYPE]: Conditional[typeof COTYPE]\n #conditionals: Conditional[]\n #otherwiseCallback: UnionNoMatchCallback<Record<string, unknown>> = (_, field) => {\n field.report(messages.unionGroup, 'unionGroup', field)\n }\n constructor(conditionals: Conditional[]) {\n this.#conditionals = conditionals\n }\n /**\n * Clones the ObjectGroup schema type.",
"score": 0.866422176361084
}
] | typescript | 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/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": 0.9684439301490784
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9465949535369873
},
{
"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": 0.945792555809021
},
{
"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": 0.927817165851593
},
{
"filename": "src/schema/boolean/main.ts",
"retrieved_chunk": " * implemented for \"unionOfTypes\"\n */\n [IS_OF_TYPE] = (value: unknown) => {\n const valueAsBoolean = this.options.strict === true ? value : helpers.asBoolean(value)\n return typeof valueAsBoolean === 'boolean'\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {",
"score": 0.9215980172157288
}
] | typescript | 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": 0.9678938984870911
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9434553384780884
},
{
"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": 0.9414482712745667
},
{
"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": 0.9310442209243774
},
{
"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": 0.9258049726486206
}
] | 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 { 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/number/main.ts",
"retrieved_chunk": " return !Number.isNaN(valueAsNumber)\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {\n super(options, validations || [numberRule(options || {})])\n }\n /**\n * Enforce a minimum value for the number input",
"score": 0.9241530299186707
},
{
"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": 0.9175865650177002
},
{
"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": 0.9146019220352173
},
{
"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": 0.9078339338302612
},
{
"filename": "src/schema/array/main.ts",
"retrieved_chunk": " return Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an array field\n */\n minLength(expectedLength: number) {",
"score": 0.906886100769043
}
] | typescript | options, validations || [enumRule({ choices: values })])
this.#values = values
} |
/*
* @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": " characterSet += '-'\n }\n if (options.allowUnderscores) {\n characterSet += '_'\n }\n }\n const expression = new RegExp(`^[${characterSet}]+$`)\n if (!expression.test(value as string)) {\n field.report(messages.alpha, 'alpha', field)\n }",
"score": 0.7774320244789124
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " }\n const expression = new RegExp(`^[${characterSet}]+$`)\n if (!expression.test(value as string)) {\n field.report(messages.alphaNumeric, 'alphaNumeric', field)\n }\n }\n)\n/**\n * Enforce a minimum length on a string field\n */",
"score": 0.769146203994751
},
{
"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": 0.7650434970855713
},
{
"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": 0.7607881426811218
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " const choices = typeof options.choices === 'function' ? options.choices(field) : options.choices\n /**\n * Performing validation and reporting error\n */\n if (!choices.includes(value as string)) {\n field.report(messages.in, 'in', field, options)\n return\n }\n }\n)",
"score": 0.7595572471618652
}
] | typescript | field.report(messages.decimal, 'decimal', field, { digits: options.range.join('-') })
} |
/*
* @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": " * Ensure the value ends with the pre-defined substring\n */\nexport const endsWithRule = createRule<{ substring: string }>((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).endsWith(options.substring)) {",
"score": 0.9326002597808838
},
{
"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": 0.932487964630127
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " }\n})\n/**\n * Validates the value to be a valid IP address.\n */\nexport const ipAddressRule = createRule<{ version: 4 | 6 } | undefined>((value, options, field) => {\n if (!field.isValid) {\n return\n }\n if (!helpers.isIP(value as string, options?.version)) {",
"score": 0.9282928109169006
},
{
"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": 0.927920401096344
},
{
"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": 0.9262114763259888
}
] | 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/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": 0.8766360282897949
},
{
"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": 0.8712047338485718
},
{
"filename": "src/schema/union/builder.ts",
"retrieved_chunk": "import type { FieldContext, SchemaTypes } from '../../types.js'\n/**\n * Create a new union schema type. A union is a collection of conditionals\n * and schema associated with it.\n */\nexport function union<Conditional extends UnionConditional<any>>(conditionals: Conditional[]) {\n return new VineUnion<Conditional>(conditionals)\n}\n/**\n * Wrap object properties inside a conditonal",
"score": 0.8651991486549377
},
{
"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": 0.86129230260849
},
{
"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": 0.8591052293777466
}
] | 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": 0.9060301184654236
},
{
"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": 0.8967167139053345
},
{
"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": 0.8724467158317566
},
{
"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": 0.844737708568573
},
{
"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": 0.8191946744918823
}
] | 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/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": 0.8763848543167114
},
{
"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": 0.8737027645111084
},
{
"filename": "src/schema/union/builder.ts",
"retrieved_chunk": "import type { FieldContext, SchemaTypes } from '../../types.js'\n/**\n * Create a new union schema type. A union is a collection of conditionals\n * and schema associated with it.\n */\nexport function union<Conditional extends UnionConditional<any>>(conditionals: Conditional[]) {\n return new VineUnion<Conditional>(conditionals)\n}\n/**\n * Wrap object properties inside a conditonal",
"score": 0.871166467666626
},
{
"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": 0.8688561916351318
},
{
"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": 0.865602970123291
}
] | 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": 0.9169508218765259
},
{
"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": 0.7925964593887329
},
{
"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": 0.7889781594276428
},
{
"filename": "src/schema/accepted/main.ts",
"retrieved_chunk": " }\n constructor(options?: Partial<FieldOptions>, validations?: Validation<any>[]) {\n super(options, validations || [acceptedRule()])\n }\n /**\n * Clones the VineAccepted schema type. The applied options\n * and validations are copied to the new instance\n */\n clone(): this {\n return new VineAccepted(this.cloneOptions(), this.cloneValidations()) as this",
"score": 0.7871723175048828
},
{
"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": 0.7816908359527588
}
] | typescript | cloneValidations()
)
this.#groups.forEach((group) => cloned.merge(group))
if (this.#allowUnknownProperties) { |
/*
* @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})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {",
"score": 0.9213042855262756
},
{
"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": 0.9169780015945435
},
{
"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": 0.9169209003448486
},
{
"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": 0.9164465665817261
},
{
"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": 0.9162759184837341
}
] | 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 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": 0.8863018751144409
},
{
"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": 0.881837785243988
},
{
"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": 0.8613637685775757
},
{
"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": 0.8585948944091797
},
{
"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": 0.8573631644248962
}
] | typescript | if (!helpers.isMobilePhone(value as string, locales, normalizedOptions)) { |
/*
* 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": 0.9695461392402649
},
{
"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": 0.9661531448364258
},
{
"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": 0.9615675210952759
},
{
"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": 0.9529418349266052
},
{
"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": 0.9469099044799805
}
] | 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/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": 0.9277804493904114
},
{
"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": 0.9244821071624756
},
{
"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": 0.9239597916603088
},
{
"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": 0.9199525117874146
},
{
"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": 0.908084511756897
}
] | typescript | !helpers.isHexColor(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 { 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": 0.9151633977890015
},
{
"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": 0.9058554172515869
},
{
"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": 0.9056758880615234
},
{
"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": 0.8963887691497803
},
{
"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": 0.8956272602081299
}
] | 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 { 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": 0.9469489455223083
},
{
"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": 0.9302119016647339
},
{
"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": 0.8969452977180481
},
{
"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": 0.8833369612693787
},
{
"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": 0.879783570766449
}
] | typescript | field.report(messages['record.fixedLength'], 'record.fixedLength', field, options)
} |
/*
* 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": " return !Number.isNaN(valueAsNumber)\n }\n constructor(\n options?: Partial<FieldOptions> & { strict?: boolean },\n validations?: Validation<any>[]\n ) {\n super(options, validations || [numberRule(options || {})])\n }\n /**\n * Enforce a minimum value for the number input",
"score": 0.9371036291122437
},
{
"filename": "src/schema/array/main.ts",
"retrieved_chunk": " return Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an array field\n */\n minLength(expectedLength: number) {",
"score": 0.929790735244751
},
{
"filename": "src/schema/record/main.ts",
"retrieved_chunk": " [IS_OF_TYPE] = (value: unknown) => {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n }\n constructor(schema: Schema, options?: FieldOptions, validations?: Validation<any>[]) {\n super(options, validations)\n this.#schema = schema\n }\n /**\n * Enforce a minimum length on an object field\n */",
"score": 0.9195703864097595
},
{
"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": 0.9168956875801086
},
{
"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": 0.916791558265686
}
] | 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 { 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": " */\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": 0.9230951070785522
},
{
"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": 0.913870632648468
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {",
"score": 0.8863041996955872
},
{
"filename": "src/schema/string/rules.ts",
"retrieved_chunk": " */\n if (input !== value) {\n field.report(messages.sameAs, 'sameAs', field, options)\n return\n }\n})\n/**\n * Ensure the field's value under validation is different from another field's value\n */\nexport const notSameAsRule = createRule<{ otherField: string }>((value, options, field) => {",
"score": 0.8811458945274353
},
{
"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": 0.8644654750823975
}
] | 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/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": 0.8874120712280273
},
{
"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": 0.8681803941726685
},
{
"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": 0.8645970225334167
},
{
"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": 0.8399878740310669
},
{
"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": 0.833821713924408
}
] | 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/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": 0.9045039415359497
},
{
"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": 0.8919073343276978
},
{
"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": 0.8766176700592041
},
{
"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": 0.8758082389831543
},
{
"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": 0.8751785755157471
}
] | 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/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": 0.9503426551818848
},
{
"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": 0.9325030446052551
},
{
"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": 0.9190297722816467
},
{
"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": 0.9067864418029785
},
{
"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": 0.906074047088623
}
] | 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": " */\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": 0.9752844572067261
},
{
"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": 0.9475303888320923
},
{
"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": 0.9324702620506287
},
{
"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": 0.9227784276008606
},
{
"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": 0.9225260615348816
}
] | 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": "/**\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": 0.9334951043128967
},
{
"filename": "src/schema/array/rules.ts",
"retrieved_chunk": " }\n})\n/**\n * Ensure the array is not empty\n */\nexport const notEmptyRule = createRule<undefined>((value, _, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {",
"score": 0.919797956943512
},
{
"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": 0.9118332862854004
},
{
"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": 0.9105367660522461
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {",
"score": 0.9093992114067078
}
] | 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 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": 0.929406464099884
},
{
"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": 0.9173365831375122
},
{
"filename": "src/schema/number/rules.ts",
"retrieved_chunk": " }\n})\n/**\n * Enforce a maximum value on a number field\n */\nexport const maxRule = createRule<{ max: number }>((value, options, field) => {\n /**\n * Skip if the field is not valid.\n */\n if (!field.isValid) {",
"score": 0.9154229164123535
},
{
"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": 0.9140399098396301
},
{
"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": 0.9125456809997559
}
] | 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 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": 0.9675081968307495
},
{
"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": 0.936111569404602
},
{
"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": 0.9352291226387024
},
{
"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": 0.9328645467758179
},
{
"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": 0.9283543229103088
}
] | 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/number/rules.ts",
"retrieved_chunk": " return\n }\n if ((value as number) > options.max) {\n field.report(messages.max, 'max', field, options)\n }\n})\n/**\n * Enforce a range of values on a number field.\n */\nexport const rangeRule = createRule<{ min: number; max: number }>((value, options, field) => {",
"score": 0.8900129795074463
},
{
"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": 0.8745632171630859
},
{
"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": 0.8731189966201782
},
{
"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": 0.8703952431678772
},
{
"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": 0.8675439357757568
}
] | 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/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": 0.888109028339386
},
{
"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": 0.8698883056640625
},
{
"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": 0.8692572712898254
},
{
"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": 0.8656283617019653
},
{
"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": 0.8655821084976196
}
] | 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/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": 0.8949859738349915
},
{
"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": 0.8833656311035156
},
{
"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": 0.8814958333969116
},
{
"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": 0.8811068534851074
},
{
"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": 0.8747758269309998
}
] | 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/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": 0.8128170371055603
},
{
"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": 0.8088312745094299
},
{
"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": 0.8054468631744385
},
{
"filename": "src/schema/string/main.ts",
"retrieved_chunk": " return this.use(inRule({ choices }))\n }\n /**\n * Ensure the field's value under validation is not inside the pre-defined list.\n */\n notIn(list: string[] | ((field: FieldContext) => string[])) {\n return this.use(notInRule({ list }))\n }\n /**\n * Validates the value to be a valid credit card number",
"score": 0.7999945282936096
},
{
"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": 0.7962736487388611
}
] | typescript | const matchesAnyProvider = providers.find((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 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": 0.8597432971000671
},
{
"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": 0.8414406776428223
},
{
"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": 0.8299641013145447
},
{
"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": 0.8183926343917847
},
{
"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": 0.8174608945846558
}
] | typescript | field.report(messages.confirmed, 'confirmed', field, { otherField })
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/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": 0.8226787447929382
},
{
"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": 0.8076128959655762
},
{
"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": 0.8073815703392029
},
{
"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": 0.805459201335907
},
{
"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": 0.8050390481948853
}
] | typescript | .report(messages.creditCard, 'creditCard', field, { |
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-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": 0.9352691173553467
},
{
"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": 0.9038539528846741
},
{
"filename": "src/service-utilizations/aws-ecs-utilization.ts",
"retrieved_chunk": " `${targetScaleOption.memory} MiB.`,\n monthlySavings: monthlyCost - targetMonthlyCost\n }\n });\n }\n }\n async getRegionalUtilization (credentials: any, region: string, overrides?: AwsEcsUtilizationOverrides) {\n this.ecsClient = new ECS({\n credentials,\n region",
"score": 0.8991119265556335
},
{
"filename": "src/service-utilizations/rds-utilization.tsx",
"retrieved_chunk": " totalCost: 0,\n instanceCost: 0,\n totalStorageCost: 0,\n iopsCost: 0,\n throughputCost: 0\n } as RdsCosts;\n } \n }\n async getUtilization (\n awsCredentialsProvider: AwsCredentialsProvider, regions: string[], _overrides?: AwsServiceOverrides",
"score": 0.8952206373214722
},
{
"filename": "src/aws-utilization-provider.ts",
"retrieved_chunk": " for (const service of this.services) {\n this.utilizationClasses[service] = AwsServiceUtilizationFactory.createObject(service);\n }\n }\n async refreshUtilizationData (\n service: AwsResourceType, \n credentialsProvider: AwsCredentialsProvider,\n region: string,\n overrides?: AwsServiceOverrides\n ): Promise<Utilization<string>> {",
"score": 0.8917862176895142
}
] | typescript | awsCredentialsProvider: AwsCredentialsProvider, regions?: string[], overrides?: AwsServiceOverrides
) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.