[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-3670":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":25,"hasPages":23,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":27,"readmeContent":28,"aiSummary":29,"trendingCount":16,"starSnapshotCount":16,"syncStatus":18,"lastSyncTime":30,"discoverSource":31},3670,"yup","jquense\u002Fyup","jquense","Dead simple Object schema validation","",null,"TypeScript",23674,939,74,162,0,1,2,7,3,43.92,"MIT License",false,"master",true,[],"2026-06-12 02:00:52","# Yup\n\nYup is a schema builder for runtime value parsing and validation. Define a schema, transform a value to match, assert the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformation.\n\n> **You are viewing docs for the v1.0.0 of yup, pre-v1 docs are available: [here](https:\u002F\u002Fgithub.com\u002Fjquense\u002Fyup\u002Ftree\u002Fpre-v1)**\n\n**Killer Features**:\n\n- Concise yet expressive schema interface, equipped to model simple to complex data models\n- Powerful TypeScript support. Infer static types from schema, or ensure schema correctly implement a type\n- Built-in async validation support. Model server-side and client-side validation equally well\n- Extensible: add your own type-safe methods and schema\n- Rich error details, make debugging a breeze\n- Compatible with [Standard Schema](https:\u002F\u002Fgithub.com\u002Fstandard-schema\u002Fstandard-schema)\n\n## Getting Started\n\nSchema are comprised of parsing actions (transforms) as well as assertions (tests) about the input value.\nValidate an input value to parse it and run the configured set of assertions. Chain together methods to build a schema.\n\n```ts\nimport { object, string, number, date, InferType } from 'yup';\n\nlet userSchema = object({\n  name: string().required(),\n  age: number().required().positive().integer(),\n  email: string().email(),\n  website: string().url().nullable(),\n  createdOn: date().default(() => new Date()),\n});\n\n\u002F\u002F parse and assert validity\nlet user = await userSchema.validate(await fetchUser());\n\ntype User = InferType\u003Ctypeof userSchema>;\n\u002F* {\n  name: string;\n  age: number;\n  email?: string | undefined\n  website?: string | null | undefined\n  createdOn: Date\n}*\u002F\n```\n\nUse a schema to coerce or \"cast\" an input value into the correct type, and optionally\ntransform that value into more concrete and specific values, without making further assertions.\n\n```ts\n\u002F\u002F Attempts to coerce values to the correct type\nlet parsedUser = userSchema.cast({\n  name: 'jimmy',\n  age: '24',\n  createdOn: '2014-09-23T19:25:25Z',\n});\n\u002F\u002F ✅  { name: 'jimmy', age: 24, createdOn: Date }\n```\n\nKnow that your input value is already parsed? You can \"strictly\" validate an input, and avoid the overhead\nof running parsing logic.\n\n```ts\n\u002F\u002F ❌  ValidationError \"age is not a number\"\nlet parsedUser = await userSchema.validate(\n  {\n    name: 'jimmy',\n    age: '24',\n  },\n  { strict: true },\n);\n```\n\n## Table of Contents\n\n\u003C!-- START doctoc generated TOC please keep comment here to allow auto update -->\n\u003C!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n\n- [Schema basics](#schema-basics)\n  - [Parsing: Transforms](#parsing-transforms)\n  - [Validation: Tests](#validation-tests)\n    - [Customizing errors](#customizing-errors)\n  - [Composition and Reuse](#composition-and-reuse)\n- [TypeScript integration](#typescript-integration)\n  - [Schema defaults](#schema-defaults)\n  - [Ensuring a schema matches an existing type](#ensuring-a-schema-matches-an-existing-type)\n  - [Extending built-in schema with new methods](#extending-built-in-schema-with-new-methods)\n  - [TypeScript configuration](#typescript-configuration)\n- [Error message customization](#error-message-customization)\n  - [localization and i18n](#localization-and-i18n)\n- [Standard Schema Support](#standard-schema-support)\n- [API](#api)\n  - [`yup`](#yup)\n    - [`reach(schema: Schema, path: string, value?: object, context?: object): Schema`](#reachschema-schema-path-string-value-object-context-object-schema)\n    - [`addMethod(schemaType: Schema, name: string, method: ()=> Schema): void`](#addmethodschematype-schema-name-string-method--schema-void)\n    - [`ref(path: string, options: { contextPrefix: string }): Ref`](#refpath-string-options--contextprefix-string--ref)\n    - [`lazy((value: any) => Schema): Lazy`](#lazyvalue-any--schema-lazy)\n    - [`ValidationError(errors: string | Array\u003Cstring>, value: any, path: string)`](#validationerrorerrors-string--arraystring-value-any-path-string)\n  - [`Schema`](#schema)\n    - [`Schema.clone(): Schema`](#schemaclone-schema)\n    - [`Schema.label(label: string): Schema`](#schemalabellabel-string-schema)\n    - [`Schema.meta(metadata: SchemaMetadata): Schema`](#schemametametadata-schemametadata-schema)\n    - [`Schema.describe(options?: ResolveOptions): SchemaDescription`](#schemadescribeoptions-resolveoptions-schemadescription)\n    - [`Schema.concat(schema: Schema): Schema`](#schemaconcatschema-schema-schema)\n    - [`Schema.validate(value: any, options?: object): Promise\u003CInferType\u003CSchema>, ValidationError>`](#schemavalidatevalue-any-options-object-promiseinfertypeschema-validationerror)\n    - [`Schema.validateSync(value: any, options?: object): InferType\u003CSchema>`](#schemavalidatesyncvalue-any-options-object-infertypeschema)\n    - [`Schema.validateAt(path: string, value: any, options?: object): Promise\u003CInferType\u003CSchema>, ValidationError>`](#schemavalidateatpath-string-value-any-options-object-promiseinfertypeschema-validationerror)\n    - [`Schema.validateSyncAt(path: string, value: any, options?: object): InferType\u003CSchema>`](#schemavalidatesyncatpath-string-value-any-options-object-infertypeschema)\n    - [`Schema.isValid(value: any, options?: object): Promise\u003Cboolean>`](#schemaisvalidvalue-any-options-object-promiseboolean)\n    - [`Schema.isValidSync(value: any, options?: object): boolean`](#schemaisvalidsyncvalue-any-options-object-boolean)\n    - [`Schema.cast(value: any, options = {}): InferType\u003CSchema>`](#schemacastvalue-any-options---infertypeschema)\n    - [`Schema.isType(value: any): value is InferType\u003CSchema>`](#schemaistypevalue-any-value-is-infertypeschema)\n    - [`Schema.strict(enabled: boolean = false): Schema`](#schemastrictenabled-boolean--false-schema)\n    - [`Schema.strip(enabled: boolean = true): Schema`](#schemastripenabled-boolean--true-schema)\n    - [`Schema.withMutation(builder: (current: Schema) => void): void`](#schemawithmutationbuilder-current-schema--void-void)\n    - [`Schema.default(value: any): Schema`](#schemadefaultvalue-any-schema)\n    - [`Schema.getDefault(options?: object): Any`](#schemagetdefaultoptions-object-any)\n    - [`Schema.nullable(message?: string | function): Schema`](#schemanullablemessage-string--function-schema)\n    - [`Schema.nonNullable(message?: string | function): Schema`](#schemanonnullablemessage-string--function-schema)\n    - [`Schema.defined(): Schema`](#schemadefined-schema)\n    - [`Schema.optional(): Schema`](#schemaoptional-schema)\n    - [`Schema.required(message?: string | function): Schema`](#schemarequiredmessage-string--function-schema)\n    - [`Schema.notRequired(): Schema`](#schemanotrequired-schema)\n    - [`Schema.typeError(message: string): Schema`](#schematypeerrormessage-string-schema)\n    - [`Schema.oneOf(arrayOfValues: Array\u003Cany>, message?: string | function): Schema` Alias: `equals`](#schemaoneofarrayofvalues-arrayany-message-string--function-schema-alias-equals)\n    - [`Schema.notOneOf(arrayOfValues: Array\u003Cany>, message?: string | function)`](#schemanotoneofarrayofvalues-arrayany-message-string--function)\n    - [`Schema.when(keys: string | string[], builder: object | (values: any[], schema) => Schema): Schema`](#schemawhenkeys-string--string-builder-object--values-any-schema--schema-schema)\n    - [`Schema.test(name: string, message: string | function | any, test: function): Schema`](#schematestname-string-message-string--function--any-test-function-schema)\n    - [`Schema.test(options: object): Schema`](#schematestoptions-object-schema)\n    - [`Schema.transform((currentValue: any, originalValue: any, schema: Schema,  options: object) => any): Schema`](#schematransformcurrentvalue-any-originalvalue-any-schema-schema--options-object--any-schema)\n  - [mixed](#mixed)\n  - [string](#string)\n    - [`string.required(message?: string | function): Schema`](#stringrequiredmessage-string--function-schema)\n    - [`string.length(limit: number | Ref, message?: string | function): Schema`](#stringlengthlimit-number--ref-message-string--function-schema)\n    - [`string.min(limit: number | Ref, message?: string | function): Schema`](#stringminlimit-number--ref-message-string--function-schema)\n    - [`string.max(limit: number | Ref, message?: string | function): Schema`](#stringmaxlimit-number--ref-message-string--function-schema)\n    - [`string.matches(regex: Regex, message?: string | function): Schema`](#stringmatchesregex-regex-message-string--function-schema)\n    - [`string.matches(regex: Regex, options: { message: string, excludeEmptyString: bool }): Schema`](#stringmatchesregex-regex-options--message-string-excludeemptystring-bool--schema)\n    - [`string.email(message?: string | function): Schema`](#stringemailmessage-string--function-schema)\n    - [`string.url(message?: string | function): Schema`](#stringurlmessage-string--function-schema)\n    - [`string.uuid(message?: string | function): Schema`](#stringuuidmessage-string--function-schema)\n    - [`string.datetime(options?: {message?: string | function, allowOffset?: boolean, precision?: number})`](#stringdatetimeoptions-message-string--function-allowoffset-boolean-precision-number)\n    - [`string.datetime(message?: string | function)`](#stringdatetimemessage-string--function)\n    - [`string.ensure(): Schema`](#stringensure-schema)\n    - [`string.trim(message?: string | function): Schema`](#stringtrimmessage-string--function-schema)\n    - [`string.lowercase(message?: string | function): Schema`](#stringlowercasemessage-string--function-schema)\n    - [`string.uppercase(message?: string | function): Schema`](#stringuppercasemessage-string--function-schema)\n  - [number](#number)\n    - [`number.min(limit: number | Ref, message?: string | function): Schema`](#numberminlimit-number--ref-message-string--function-schema)\n    - [`number.max(limit: number | Ref, message?: string | function): Schema`](#numbermaxlimit-number--ref-message-string--function-schema)\n    - [`number.lessThan(max: number | Ref, message?: string | function): Schema`](#numberlessthanmax-number--ref-message-string--function-schema)\n    - [`number.moreThan(min: number | Ref, message?: string | function): Schema`](#numbermorethanmin-number--ref-message-string--function-schema)\n    - [`number.positive(message?: string | function): Schema`](#numberpositivemessage-string--function-schema)\n    - [`number.negative(message?: string | function): Schema`](#numbernegativemessage-string--function-schema)\n    - [`number.integer(message?: string | function): Schema`](#numberintegermessage-string--function-schema)\n    - [`number.truncate(): Schema`](#numbertruncate-schema)\n    - [`number.round(type: 'floor' | 'ceil' | 'trunc' | 'round' = 'round'): Schema`](#numberroundtype-floor--ceil--trunc--round--round-schema)\n  - [boolean](#boolean)\n  - [date](#date)\n    - [`date.min(limit: Date | string | Ref, message?: string | function): Schema`](#dateminlimit-date--string--ref-message-string--function-schema)\n    - [`date.max(limit: Date | string | Ref, message?: string | function): Schema`](#datemaxlimit-date--string--ref-message-string--function-schema)\n  - [array](#array)\n    - [`array.of(type: Schema): this`](#arrayoftype-schema-this)\n    - [`array.json(): this`](#arrayjson-this)\n    - [`array.length(length: number | Ref, message?: string | function): this`](#arraylengthlength-number--ref-message-string--function-this)\n    - [`array.min(limit: number | Ref, message?: string | function): this`](#arrayminlimit-number--ref-message-string--function-this)\n    - [`array.max(limit: number | Ref, message?: string | function): this`](#arraymaxlimit-number--ref-message-string--function-this)\n    - [`array.ensure(): this`](#arrayensure-this)\n    - [`array.compact(rejector: (value) => boolean): Schema`](#arraycompactrejector-value--boolean-schema)\n  - [tuple](#tuple)\n  - [object](#object)\n    - [Object schema defaults](#object-schema-defaults)\n    - [`object.shape(fields: object, noSortEdges?: Array\u003C[string, string]>): Schema`](#objectshapefields-object-nosortedges-arraystring-string-schema)\n    - [`object.json(): this`](#objectjson-this)\n    - [`object.concat(schemaB: ObjectSchema): ObjectSchema`](#objectconcatschemab-objectschema-objectschema)\n    - [`object.pick(keys: string[]): Schema`](#objectpickkeys-string-schema)\n    - [`object.omit(keys: string[]): Schema`](#objectomitkeys-string-schema)\n    - [`object.from(fromKey: string, toKey: string, alias: boolean = false): this`](#objectfromfromkey-string-tokey-string-alias-boolean--false-this)\n    - [`object.exact(message?: string | function): Schema`](#objectexactmessage-string--function-schema)\n    - [`object.stripUnknown(): Schema`](#objectstripunknown-schema)\n    - [`object.noUnknown(onlyKnownKeys: boolean = true, message?: string | function): Schema`](#objectnounknownonlyknownkeys-boolean--true-message-string--function-schema)\n    - [`object.camelCase(): Schema`](#objectcamelcase-schema)\n    - [`object.constantCase(): Schema`](#objectconstantcase-schema)\n\n\u003C!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n## Schema basics\n\nSchema definitions, are comprised of parsing \"transforms\" which manipulate inputs into the desired shape and type, \"tests\", which make assertions over parsed data. Schema also store a bunch of \"metadata\", details about the schema itself, which can be used to improve error messages, build tools that dynamically consume schema, or serialize schema into another format.\n\nIn order to be maximally flexible yup allows running both parsing and assertions separately to match specific needs\n\n### Parsing: Transforms\n\nEach built-in type implements basic type parsing, which comes in handy when parsing serialized data, such as JSON.\nAdditionally types implement type specific transforms that can be enabled.\n\n```ts\nlet num = number().cast('1'); \u002F\u002F 1\n\nlet obj = object({\n  firstName: string().lowercase().trim(),\n})\n  .json()\n  .camelCase()\n  .cast('{\"first_name\": \"jAnE \"}'); \u002F\u002F { firstName: 'jane' }\n```\n\nCustom transforms can be added\n\n```ts\nlet reversedString = string()\n  .transform((currentValue) => currentValue.split('').reverse().join(''))\n  .cast('dlrow olleh'); \u002F\u002F \"hello world\"\n```\n\nTransforms form a \"pipeline\", where the value of a previous transform is piped into the next one.\nWhen an input value is `undefined` yup will apply the schema default if it's configured.\n\n> Watch out! values are not guaranteed to be valid types in transform functions. Previous transforms\n> may have failed. For example a number transform may be receive the input value, `NaN`, or a number.\n\n### Validation: Tests\n\nYup schema run \"tests\" over input values. Tests assert that inputs conform to some\ncriteria. Tests are distinct from transforms, in that they do not change or alter the input (or its type)\nand are usually reserved for checks that are hard, if not impossible, to represent in static types.\n\n```ts\nstring()\n  .min(3, 'must be at least 3 characters long')\n  .email('must be a valid email')\n  .validate('no'); \u002F\u002F ValidationError\n```\n\nAs with transforms, tests can be customized on the fly\n\n```ts\nlet jamesSchema = string().test(\n  'is-james',\n  (d) => `${d.path} is not James`,\n  (value) => value == null || value === 'James',\n);\n\njamesSchema.validateSync('James'); \u002F\u002F \"James\"\n\njamesSchema.validateSync('Jane'); \u002F\u002F ValidationError \"this is not James\"\n```\n\n> Heads up: unlike transforms, `value` in a custom test is guaranteed to be the correct type\n> (in this case an optional string). It still may be `undefined` or `null` depending on your schema\n> in those cases, you may want to return `true` for absent values unless your transform makes presence\n> related assertions. The test option `skipAbsent` will do this for you if set.\n\n#### Customizing errors\n\nIn the simplest case a test function returns `true` or `false` depending on the whether the check\npassed. In the case of a failing test, yup will throw\na [`ValidationError`](#validationerrorerrors-string--arraystring-value-any-path-string) with your (or the default)\nmessage for that test. ValidationErrors also contain a bunch of other metadata about the test,\nincluding it's name, what arguments (if any) it was called with, and the path to the failing field\nin the case of a nested validation.\n\nError messages can also be constructed on the fly to customize how the schema fails.\n\n```ts\nlet order = object({\n  no: number().required(),\n  sku: string().test({\n    name: 'is-sku',\n    skipAbsent: true,\n    test(value, ctx) {\n      if (!value.startsWith('s-')) {\n        return ctx.createError({ message: 'SKU missing correct prefix' });\n      }\n      if (!value.endsWith('-42a')) {\n        return ctx.createError({ message: 'SKU missing correct suffix' });\n      }\n      if (value.length \u003C 10) {\n        return ctx.createError({ message: 'SKU is not the right length' });\n      }\n      return true;\n    },\n  }),\n});\n\norder.validate({ no: 1234, sku: 's-1a45-14a' });\n```\n\n### Composition and Reuse\n\nSchema are immutable, each method call returns a new schema object. Reuse and pass them around without\nfear of mutating another instance.\n\n```ts\nlet optionalString = string().optional();\n\nlet definedString = optionalString.defined();\n\nlet value = undefined;\noptionalString.isValid(value); \u002F\u002F true\ndefinedString.isValid(value); \u002F\u002F false\n```\n\n## TypeScript integration\n\nYup schema produce static TypeScript interfaces. Use `InferType` to extract that interface:\n\n```ts\nimport * as yup from 'yup';\n\nlet personSchema = yup.object({\n  firstName: yup.string().defined(),\n  nickName: yup.string().default('').nullable(),\n  sex: yup\n    .mixed()\n    .oneOf(['male', 'female', 'other'] as const)\n    .defined(),\n  email: yup.string().nullable().email(),\n  birthDate: yup.date().nullable().min(new Date(1900, 0, 1)),\n});\n\ninterface Person extends yup.InferType\u003Ctypeof personSchema> {\n  \u002F\u002F using interface instead of type generally gives nicer editor feedback\n}\n```\n\n### Schema defaults\n\nA schema's default is used when casting produces an `undefined` output value. Because of this,\nsetting a default affects the output type of the schema, essentially marking it as \"defined()\".\n\n```ts\nimport { string } from 'yup';\n\nlet value: string = string().default('hi').validate(undefined);\n\n\u002F\u002F vs\n\nlet value: string | undefined = string().validate(undefined);\n```\n\n### Ensuring a schema matches an existing type\n\nIn some cases a TypeScript type already exists, and you want to ensure that\nyour schema produces a compatible type:\n\n```ts\nimport { object, number, string, ObjectSchema } from 'yup';\n\ninterface Person {\n  name: string;\n  age?: number;\n  sex: 'male' | 'female' | 'other' | null;\n}\n\n\u002F\u002F will raise a compile-time type error if the schema does not produce a valid Person\nlet schema: ObjectSchema\u003CPerson> = object({\n  name: string().defined(),\n  age: number().optional(),\n  sex: string\u003C'male' | 'female' | 'other'>().nullable().defined(),\n});\n\n\u002F\u002F ❌ errors:\n\u002F\u002F \"Type 'number | undefined' is not assignable to type 'string'.\"\nlet badSchema: ObjectSchema\u003CPerson> = object({\n  name: number(),\n});\n```\n\n### Extending built-in schema with new methods\n\nYou can use TypeScript's interface merging behavior to extend the schema types\nif needed. Type extensions should go in an \"ambient\" type definition file such as your\n`globals.d.ts`. Remember to actually extend the yup type in your application code!\n\n> Watch out! merging only works if the type definition is _exactly_ the same, including\n> generics. Consult the yup source code for each type to ensure you are defining it correctly\n\n```ts\n\u002F\u002F globals.d.ts\ndeclare module 'yup' {\n  interface StringSchema\u003CTType, TContext, TDefault, TFlags> {\n    append(appendStr: string): this;\n  }\n}\n\n\u002F\u002F app.ts\nimport { addMethod, string } from 'yup';\n\naddMethod(string, 'append', function append(appendStr: string) {\n  return this.transform((value) => `${value}${appendStr}`);\n});\n\nstring().append('~~~~').cast('hi'); \u002F\u002F 'hi~~~~'\n```\n\n### TypeScript configuration\n\nYou **must** have the `strictNullChecks` compiler option enabled for type inference to work.\n\nWe also recommend settings `strictFunctionTypes` to `false`, for functionally better types. Yes\nthis reduces overall soundness, however TypeScript already disables this check\nfor methods and constructors (note from TS docs):\n\n> During development of this feature, we discovered a large number of inherently\n> unsafe class hierarchies, including some in the DOM. Because of this,\n> the setting only applies to functions written in function syntax, not to those in method syntax:\n\nYour mileage will vary, but we've found that this check doesn't prevent many of\nreal bugs, while increasing the amount of onerous explicit type casting in apps.\n\n## Error message customization\n\nDefault error messages can be customized for when no message is provided with a validation test.\nIf any message is missing in the custom dictionary the error message will default to Yup's one.\n\n```js\nimport { setLocale } from 'yup';\n\nsetLocale({\n  mixed: {\n    default: 'Não é válido',\n  },\n  number: {\n    min: 'Deve ser maior que ${min}',\n  },\n});\n\n\u002F\u002F now use Yup schemas AFTER you defined your custom dictionary\nlet schema = yup.object().shape({\n  name: yup.string(),\n  age: yup.number().min(18),\n});\n\ntry {\n  await schema.validate({ name: 'jimmy', age: 11 });\n} catch (err) {\n  err.name; \u002F\u002F => 'ValidationError'\n  err.errors; \u002F\u002F => ['Deve ser maior que 18']\n}\n```\n\n### localization and i18n\n\nIf you need multi-language support, yup has got you covered. The function `setLocale` accepts functions that can be used to\ngenerate error objects with translation keys and values. These can be fed it into your favorite i18n library.\n\n```js\nimport { setLocale } from 'yup';\n\nsetLocale({\n  \u002F\u002F use constant translation keys for messages without values\n  mixed: {\n    default: 'field_invalid',\n  },\n  \u002F\u002F use functions to generate an error object that includes the value from the schema\n  number: {\n    min: ({ min }) => ({ key: 'field_too_short', values: { min } }),\n    max: ({ max }) => ({ key: 'field_too_big', values: { max } }),\n  },\n});\n\n\u002F\u002F ...\n\nlet schema = yup.object().shape({\n  name: yup.string(),\n  age: yup.number().min(18),\n});\n\ntry {\n  await schema.validate({ name: 'jimmy', age: 11 });\n} catch (err) {\n  messages = err.errors.map((err) => i18next.t(err.key));\n}\n```\n\n## Standard Schema Support\n\nYup is compatible with [Standard Schema](https:\u002F\u002Fgithub.com\u002Fstandard-schema\u002Fstandard-schema).\n\n## API\n\n### `yup`\n\nThe module export.\n\n```ts\n\u002F\u002F core schema\nimport {\n  mixed,\n  string,\n  number,\n  boolean,\n  bool,\n  date,\n  object,\n  array,\n  ref,\n  lazy,\n} from 'yup';\n\n\u002F\u002F Classes\nimport {\n  Schema,\n  MixedSchema,\n  StringSchema,\n  NumberSchema,\n  BooleanSchema,\n  DateSchema,\n  ArraySchema,\n  ObjectSchema,\n} from 'yup';\n\n\u002F\u002F Types\nimport type { InferType, ISchema, AnySchema, AnyObjectSchema } from 'yup';\n```\n\n#### `reach(schema: Schema, path: string, value?: object, context?: object): Schema`\n\nFor nested schemas, `reach` will retrieve an inner schema based on the provided path.\n\nFor nested schemas that need to resolve dynamically, you can provide a `value` and optionally\na `context` object.\n\n```js\nimport { reach } from 'yup';\n\nlet schema = object({\n  nested: object({\n    arr: array(object({ num: number().max(4) })),\n  }),\n});\n\nreach(schema, 'nested.arr.num');\nreach(schema, 'nested.arr[].num');\nreach(schema, 'nested.arr[1].num');\nreach(schema, 'nested[\"arr\"][1].num');\n```\n\n#### `addMethod(schemaType: Schema, name: string, method: ()=> Schema): void`\n\nAdds a new method to the core schema types. A friendlier convenience method for `schemaType.prototype[name] = method`.\n\n```ts\nimport { addMethod, date } from 'yup';\n\naddMethod(date, 'format', function format(formats, parseStrict) {\n  return this.transform((value, originalValue, ctx) => {\n    if (ctx.isType(value)) return value;\n\n    value = Moment(originalValue, formats, parseStrict);\n\n    return value.isValid() ? value.toDate() : new Date('');\n  });\n});\n```\n\nIf you want to add a method to ALL schema types, extend the abstract base class: `Schema`\n\n```ts\nimport { addMethod, Schema } from 'yup';\n\naddMethod(Schema, 'myMethod', ...)\n```\n\n#### `ref(path: string, options: { contextPrefix: string }): Ref`\n\nCreates a reference to another sibling or sibling descendant field. Refs are resolved\nat _validation\u002Fcast time_ and supported where specified. Refs are evaluated in the proper order so that\nthe ref value is resolved before the field using the ref (be careful of circular dependencies!).\n\n```js\nimport { ref, object, string } from 'yup';\n\nlet schema = object({\n  baz: ref('foo.bar'),\n  foo: object({\n    bar: string(),\n  }),\n  x: ref('$x'),\n});\n\nschema.cast({ foo: { bar: 'boom' } }, { context: { x: 5 } });\n\u002F\u002F => { baz: 'boom',  x: 5, foo: { bar: 'boom' } }\n```\n\n#### `lazy((value: any) => Schema): Lazy`\n\nCreates a schema that is evaluated at validation\u002Fcast time. Useful for creating\nrecursive schema like Trees, for polymorphic fields and arrays.\n\n**CAUTION!** When defining parent-child recursive object schema, you want to reset the `default()`\nto `null` on the child—otherwise the object will infinitely nest itself when you cast it!\n\n```js\nlet node = object({\n  id: number(),\n  child: yup.lazy(() => node.default(undefined)),\n});\n\nlet renderable = yup.lazy((value) => {\n  switch (typeof value) {\n    case 'number':\n      return number();\n    case 'string':\n      return string();\n    default:\n      return mixed();\n  }\n});\n\nlet renderables = array().of(renderable);\n```\n\n#### `ValidationError(errors: string | Array\u003Cstring>, value: any, path: string)`\n\nThrown on failed validations, with the following properties\n\n- `name`: \"ValidationError\"\n- `type`: the specific test type or test \"name\", that failed.\n- `value`: The field value that was tested;\n- `params`?: The test inputs, such as max value, regex, etc;\n- `path`: a string, indicating where there error was thrown. `path` is empty at the root level.\n- `errors`: array of error messages\n- `inner`: in the case of aggregate errors, inner is an array of `ValidationErrors` throw earlier in the\n  validation chain. When the `abortEarly` option is `false` this is where you can inspect each error thrown,\n  alternatively, `errors` will have all of the messages from each inner error.\n\n### `Schema`\n\n`Schema` is the abstract base class that all schema type inherit from. It provides a number of base methods and properties\nto all other schema types.\n\n> Note: unless you are creating a custom schema type, Schema should never be used directly. For unknown\u002Fany types use [`mixed()`](#mixed)\n\n#### `Schema.clone(): Schema`\n\nCreates a deep copy of the schema. Clone is used internally to return a new schema with every schema state change.\n\n#### `Schema.label(label: string): Schema`\n\nOverrides the key name which is used in error messages.\n\n#### `Schema.meta(metadata: SchemaMetadata): Schema`\n\nAdds to a metadata object, useful for storing data with a schema, that doesn't belong\nto the cast object itself.\n\nA custom `SchemaMetadata` interface can be defined through\n[merging](https:\u002F\u002Fwww.typescriptlang.org\u002Fdocs\u002Fhandbook\u002Fdeclaration-merging.html#merging-interfaces)\nwith the `CustomSchemaMetadata` interface. Start by creating a `yup.d.ts` file\nin your package and creating your desired `CustomSchemaMetadata` interface:\n\n```ts\n\u002F\u002F yup.d.ts\nimport 'yup';\n\ndeclare module 'yup' {\n  \u002F\u002F Define your desired `SchemaMetadata` interface by merging the\n  \u002F\u002F `CustomSchemaMetadata` interface.\n  export interface CustomSchemaMetadata {\n    placeholderText?: string;\n    tooltipText?: string;\n    \u002F\u002F …\n  }\n}\n```\n\n#### `Schema.describe(options?: ResolveOptions): SchemaDescription`\n\nCollects schema details (like meta, labels, and active tests) into a serializable\ndescription object.\n\n```ts\nlet schema = object({\n  name: string().required(),\n});\n\nlet description = schema.describe();\n```\n\nFor schema with dynamic components (references, lazy, or conditions), describe requires\nmore context to accurately return the schema description. In these cases provide `options`\n\n```ts\nimport { ref, object, string, boolean } from 'yup';\n\nlet schema = object({\n  isBig: boolean(),\n  count: number().when('isBig', {\n    is: true,\n    then: (schema) => schema.min(5),\n    otherwise: (schema) => schema.min(0),\n  }),\n});\n\nschema.describe({ value: { isBig: true } });\n```\n\nAnd below are the description types, which differ a bit depending on the schema type.\n\n```ts\ninterface SchemaDescription {\n  type: string;\n  label?: string;\n  meta: object | undefined;\n  oneOf: unknown[];\n  notOneOf: unknown[];\n  default?: unknown;\n  nullable: boolean;\n  optional: boolean;\n  tests: Array\u003C{ name?: string; params: ExtraParams | undefined }>;\n\n  \u002F\u002F Present on object schema descriptions\n  fields: Record\u003Cstring, SchemaFieldDescription>;\n\n  \u002F\u002F Present on array schema descriptions\n  innerType?: SchemaFieldDescription;\n}\n\ntype SchemaFieldDescription =\n  | SchemaDescription\n  | SchemaRefDescription\n  | SchemaLazyDescription;\n\ninterface SchemaRefDescription {\n  type: 'ref';\n  key: string;\n}\n\ninterface SchemaLazyDescription {\n  type: string;\n  label?: string;\n  meta: object | undefined;\n}\n```\n\n#### `Schema.concat(schema: Schema): Schema`\n\nCreates a new instance of the schema by combining two schemas. Only schemas of the same type can be concatenated.\n`concat` is not a \"merge\" function in the sense that all settings from the provided schema, override ones in the\nbase, including type, presence and nullability.\n\n```ts\nmixed\u003Cstring>().defined().concat(mixed\u003Cnumber>().nullable());\n\n\u002F\u002F produces the equivalent to:\n\nmixed\u003Cnumber>().defined().nullable();\n```\n\n#### `Schema.validate(value: any, options?: object): Promise\u003CInferType\u003CSchema>, ValidationError>`\n\nReturns the parses and validates an input value, returning the parsed value or throwing an error. This method is **asynchronous** and returns a Promise object, that is fulfilled with the value, or rejected\nwith a `ValidationError`.\n\n```js\nvalue = await schema.validate({ name: 'jimmy', age: 24 });\n```\n\nProvide `options` to more specifically control the behavior of `validate`.\n\n```js\ninterface Options {\n  \u002F\u002F when true, parsing is skipped and the input is validated \"as-is\"\n  strict: boolean = false;\n  \u002F\u002F Throw on the first error or collect and return all\n  abortEarly: boolean = true;\n  \u002F\u002F Remove unspecified keys from objects\n  stripUnknown: boolean = false;\n  \u002F\u002F when `false` validations will be performed shallowly\n  recursive: boolean = true;\n  \u002F\u002F External values that can be provided to validations and conditionals\n  context?: object;\n}\n```\n\n#### `Schema.validateSync(value: any, options?: object): InferType\u003CSchema>`\n\nRuns validatations synchronously _if possible_ and returns the resulting value,\nor throws a ValidationError. Accepts all the same options as `validate`.\n\nSynchronous validation only works if there are no configured async tests, e.g tests that return a Promise.\nFor instance this will work:\n\n```js\nlet schema = number().test(\n  'is-42',\n  \"this isn't the number i want\",\n  (value) => value != 42,\n);\n\nschema.validateSync(23); \u002F\u002F throws ValidationError\n```\n\nhowever this will not:\n\n```js\nlet schema = number().test('is-42', \"this isn't the number i want\", (value) =>\n  Promise.resolve(value != 42),\n);\n\nschema.validateSync(42); \u002F\u002F throws Error\n```\n\n#### `Schema.validateAt(path: string, value: any, options?: object): Promise\u003CInferType\u003CSchema>, ValidationError>`\n\nValidate a deeply nested path within the schema. Similar to how `reach` works,\nbut uses the resulting schema as the subject for validation.\n\n> Note! The `value` here is the _root_ value relative to the starting schema, not the value at the nested path.\n\n```js\nlet schema = object({\n  foo: array().of(\n    object({\n      loose: boolean(),\n      bar: string().when('loose', {\n        is: true,\n        otherwise: (schema) => schema.strict(),\n      }),\n    }),\n  ),\n});\n\nlet rootValue = {\n  foo: [{ bar: 1 }, { bar: 1, loose: true }],\n};\n\nawait schema.validateAt('foo[0].bar', rootValue); \u002F\u002F => ValidationError: must be a string\n\nawait schema.validateAt('foo[1].bar', rootValue); \u002F\u002F => '1'\n```\n\n#### `Schema.validateSyncAt(path: string, value: any, options?: object): InferType\u003CSchema>`\n\nSame as `validateAt` but synchronous.\n\n#### `Schema.isValid(value: any, options?: object): Promise\u003Cboolean>`\n\nReturns `true` when the passed in value matches the schema. `isValid`\nis **asynchronous** and returns a Promise object.\n\nTakes the same options as `validate()`.\n\n#### `Schema.isValidSync(value: any, options?: object): boolean`\n\nSynchronously returns `true` when the passed in value matches the schema.\n\nTakes the same options as `validateSync()` and has the same caveats around async tests.\n\n#### `Schema.cast(value: any, options = {}): InferType\u003CSchema>`\n\nAttempts to coerce the passed in value to a value that matches the schema. For example: `'5'` will\ncast to `5` when using the `number()` type. Failed casts generally return `null`, but may also\nreturn results like `NaN` and unexpected strings.\n\nProvide `options` to more specifically control the behavior of `validate`.\n\n```js\ninterface CastOptions\u003CTContext extends {}> {\n  \u002F\u002F Remove undefined properties from objects\n  stripUnknown: boolean = false;\n\n  \u002F\u002F Throws a TypeError if casting doesn't produce a valid type\n  \u002F\u002F note that the TS return type is inaccurate when this is `false`, use with caution\n  assert?: boolean = true;\n\n  \u002F\u002F External values that used to resolve conditions and references\n  context?: TContext;\n}\n```\n\n#### `Schema.isType(value: any): value is InferType\u003CSchema>`\n\nRuns a type check against the passed in `value`. It returns true if it matches,\nit does not cast the value. When `nullable()` is set `null` is considered a valid value of the type.\nYou should use `isType` for all Schema type checks.\n\n#### `Schema.strict(enabled: boolean = false): Schema`\n\nSets the `strict` option to `true`. Strict schemas skip coercion and transformation attempts,\nvalidating the value \"as is\".\n\n#### `Schema.strip(enabled: boolean = true): Schema`\n\nMarks a schema to be removed from an output object. Only works as a nested schema.\n\n```js\nlet schema = object({\n  useThis: number(),\n  notThis: string().strip(),\n});\n\nschema.cast({ notThis: 'foo', useThis: 4 }); \u002F\u002F => { useThis: 4 }\n```\n\nSchema with `strip` enabled have an inferred type of `never`, allowing them to be\nremoved from the overall type:\n\n```ts\nlet schema = object({\n  useThis: number(),\n  notThis: string().strip(),\n});\n\nInferType\u003Ctypeof schema>; \u002F*\n{\n   useThis?: number | undefined\n}\n*\u002F\n```\n\n#### `Schema.withMutation(builder: (current: Schema) => void): void`\n\nFirst the legally required Rich Hickey quote:\n\n> If a tree falls in the woods, does it make a sound?\n>\n> If a pure function mutates some local data in order to produce an immutable return value, is that ok?\n\n`withMutation` allows you to mutate the schema in place, instead of the default behavior which clones before each change. Generally this isn't necessary since the vast majority of schema changes happen during the initial\ndeclaration, and only happen once over the lifetime of the schema, so performance isn't an issue.\nHowever certain mutations _do_ occur at cast\u002Fvalidation time, (such as conditional schema using [`when()`](#schemawhenkeys-string--string-builder-object--values-any-schema--schema-schema)), or\nwhen instantiating a schema object.\n\n```js\nobject()\n  .shape({ key: string() })\n  .withMutation((schema) => {\n    return arrayOfObjectTests.forEach((test) => {\n      schema.test(test);\n    });\n  });\n```\n\n#### `Schema.default(value: any): Schema`\n\nSets a default value to use when the value is `undefined`.\nDefaults are created after transformations are executed, but before validations, to help ensure that safe\ndefaults are specified. The default value will be cloned on each use, which can incur performance penalty\nfor objects and arrays. To avoid this overhead you can also pass a function that returns a new default.\nNote that `null` is considered a separate non-empty value.\n\n```js\nyup.string.default('nothing');\n\nyup.object.default({ number: 5 }); \u002F\u002F object will be cloned every time a default is needed\n\nyup.object.default(() => ({ number: 5 })); \u002F\u002F this is cheaper\n\nyup.date.default(() => new Date()); \u002F\u002F also helpful for defaults that change over time\n```\n\n#### `Schema.getDefault(options?: object): Any`\n\nRetrieve a previously set default value. `getDefault` will resolve any conditions that may alter the default. Optionally pass `options` with `context` (for more info on `context` see `Schema.validate`).\n\n#### `Schema.nullable(message?: string | function): Schema`\n\nIndicates that `null` is a valid value for the schema. Without `nullable()`\n`null` is treated as a different type and will fail `Schema.isType()` checks.\n\n```ts\nlet schema = number().nullable();\n\nschema.cast(null); \u002F\u002F null\n\nInferType\u003Ctypeof schema>; \u002F\u002F number | null\n```\n\n#### `Schema.nonNullable(message?: string | function): Schema`\n\nThe opposite of `nullable`, removes `null` from valid type values for the schema.\n**Schema are non nullable by default**.\n\n```ts\nlet schema = number().nonNullable();\n\nschema.cast(null); \u002F\u002F TypeError\n\nInferType\u003Ctypeof schema>; \u002F\u002F number\n```\n\n#### `Schema.defined(): Schema`\n\nRequire a value for the schema. All field values apart from `undefined` meet this requirement.\n\n```ts\nlet schema = string().defined();\n\nschema.cast(undefined); \u002F\u002F TypeError\n\nInferType\u003Ctypeof schema>; \u002F\u002F string\n```\n\n#### `Schema.optional(): Schema`\n\nThe opposite of `defined()` allows `undefined` values for the given type.\n\n```ts\nlet schema = string().optional();\n\nschema.cast(undefined); \u002F\u002F undefined\n\nInferType\u003Ctypeof schema>; \u002F\u002F string | undefined\n```\n\n#### `Schema.required(message?: string | function): Schema`\n\nMark the schema as required, which will not allow `undefined` or `null` as a value. `required`\nnegates the effects of calling `optional()` and `nullable()`\n\n> Watch out! [`string().required`](#stringrequiredmessage-string--function-schema)) works a little\n> different and additionally prevents empty string values (`''`) when required.\n\n#### `Schema.notRequired(): Schema`\n\nMark the schema as not required. This is a shortcut for `schema.nullable().optional()`;\n\n#### `Schema.typeError(message: string): Schema`\n\nDefine an error message for failed type checks. The `${value}` and `${type}` interpolation can\nbe used in the `message` argument.\n\n#### `Schema.oneOf(arrayOfValues: Array\u003Cany>, message?: string | function): Schema` Alias: `equals`\n\nOnly allow values from set of values. Values added are removed from any `notOneOf` values if present.\nThe `${values}` interpolation can be used in the `message` argument. If a ref or refs are provided,\nthe `${resolved}` interpolation can be used in the message argument to get the resolved values that were checked\nat validation time.\n\nNote that `undefined` does not fail this validator, even when `undefined` is not included in `arrayOfValues`.\nIf you don't want `undefined` to be a valid value, you can use `Schema.required`.\n\n```js\nlet schema = yup.mixed().oneOf(['jimmy', 42]);\n\nawait schema.isValid(42); \u002F\u002F => true\nawait schema.isValid('jimmy'); \u002F\u002F => true\nawait schema.isValid(new Date()); \u002F\u002F => false\n```\n\n#### `Schema.notOneOf(arrayOfValues: Array\u003Cany>, message?: string | function)`\n\nDisallow values from a set of values. Values added are removed from `oneOf` values if present.\nThe `${values}` interpolation can be used in the `message` argument. If a ref or refs are provided,\nthe `${resolved}` interpolation can be used in the message argument to get the resolved values that were checked\nat validation time.\n\n```js\nlet schema = yup.mixed().notOneOf(['jimmy', 42]);\n\nawait schema.isValid(42); \u002F\u002F => false\nawait schema.isValid(new Date()); \u002F\u002F => true\n```\n\n#### `Schema.when(keys: string | string[], builder: object | (values: any[], schema) => Schema): Schema`\n\nAdjust the schema based on a sibling or sibling children fields. You can provide an object\nliteral where the key `is` is value or a matcher function, `then` provides the true schema and\u002For\n`otherwise` for the failure condition.\n\n`is` conditions are strictly compared (`===`) if you want to use a different form of equality you\ncan provide a function like: `is: (value) => value == true`.\n\nYou can also prefix properties with `$` to specify a property that is dependent\non `context` passed in by `validate()` or `cast` instead of the input value.\n\n`when` conditions are additive.\n\n`then` and `otherwise` are specified functions `(schema: Schema) => Schema`.\n\n```js\nlet schema = object({\n  isBig: boolean(),\n  count: number()\n    .when('isBig', {\n      is: true, \u002F\u002F alternatively: (val) => val == true\n      then: (schema) => schema.min(5),\n      otherwise: (schema) => schema.min(0),\n    })\n    .when('$other', ([other], schema) =>\n      other === 4 ? schema.max(6) : schema,\n    ),\n});\n\nawait schema.validate(value, { context: { other: 4 } });\n```\n\nYou can also specify more than one dependent key, in which case each value will be spread as an argument.\n\n```js\nlet schema = object({\n  isSpecial: boolean(),\n  isBig: boolean(),\n  count: number().when(['isBig', 'isSpecial'], {\n    is: true, \u002F\u002F alternatively: (isBig, isSpecial) => isBig && isSpecial\n    then: (schema) => schema.min(5),\n    otherwise: (schema) => schema.min(0),\n  }),\n});\n\nawait schema.validate({\n  isBig: true,\n  isSpecial: true,\n  count: 10,\n});\n```\n\nAlternatively you can provide a function that returns a schema, called with an array of values for each provided key the current schema.\n\n```js\nlet schema = yup.object({\n  isBig: yup.boolean(),\n  count: yup.number().when('isBig', ([isBig], schema) => {\n    return isBig ? schema.min(5) : schema.min(0);\n  }),\n});\n\nawait schema.validate({ isBig: false, count: 4 });\n```\n\n#### `Schema.test(name: string, message: string | function | any, test: function): Schema`\n\nAdds a test function to the validation chain. Tests are run after any object is cast.\nMany types have some tests built in, but you can create custom ones easily.\nIn order to allow asynchronous custom validations _all_ (or no) tests are run asynchronously.\nA consequence of this is that test execution order cannot be guaranteed.\n\nAll tests must provide a `name`, an error `message` and a validation function that must return\n`true` when the current `value` is valid and `false` or a `ValidationError` otherwise.\nTo make a test async return a promise that resolves `true` or `false` or a `ValidationError`.\n\nFor the `message` argument you can provide a string which will interpolate certain values\nif specified using the `${param}` syntax. By default all test messages are passed a `path` value\nwhich is valuable in nested schemas.\n\nThe `test` function is called with the current `value`. For more advanced validations you can\nuse the alternate signature to provide more options (see below):\n\n```js\nlet jimmySchema = string().test(\n  'is-jimmy',\n  '${path} is not Jimmy',\n  (value, context) => value === 'jimmy',\n);\n\n\u002F\u002F or make it async by returning a promise\nlet asyncJimmySchema = string()\n  .label('First name')\n  .test(\n    'is-jimmy',\n    ({ label }) => `${label} is not Jimmy`, \u002F\u002F a message can also be a function\n    async (value, testContext) =>\n      (await fetch('\u002Fis-jimmy\u002F' + value)).responseText === 'true',\n  );\n\nawait schema.isValid('jimmy'); \u002F\u002F => true\nawait schema.isValid('john'); \u002F\u002F => false\n```\n\nTest functions are called with a special context value, as the second argument, that exposes some useful metadata\nand functions. For non arrow functions, the test context is also set as the function `this`. Watch out, if you access\nit via `this` it won't work in an arrow function.\n\n- `testContext.path`: the string path of the current validation\n- `testContext.schema`: the resolved schema object that the test is running against.\n- `testContext.options`: the `options` object that validate() or isValid() was called with\n- `testContext.parent`: in the case of nested schema, this is the value of the parent object\n- `testContext.originalValue`: the original value that is being tested\n- `testContext.createError(Object: { path: String, message: String, params: Object })`: create and return a\n  validation error. Useful for dynamically setting the `path`, `params`, or more likely, the error `message`.\n  If either option is omitted it will use the current path, or default message.\n\n#### `Schema.test(options: object): Schema`\n\nAlternative `test(..)` signature. `options` is an object containing some of the following options:\n\n```js\nOptions = {\n  \u002F\u002F unique name identifying the test\n  name: string;\n  \u002F\u002F test function, determines schema validity\n  test: (value: any) => boolean;\n  \u002F\u002F the validation error message\n  message: string;\n  \u002F\u002F values passed to message for interpolation\n  params: ?object;\n  \u002F\u002F mark the test as exclusive, meaning only one test of the same name can be active at once\n  exclusive: boolean = false;\n}\n```\n\nIn the case of mixing exclusive and non-exclusive tests the following logic is used.\nIf a non-exclusive test is added to a schema with an exclusive test of the same name\nthe exclusive test is removed and further tests of the same name will be stacked.\n\nIf an exclusive test is added to a schema with non-exclusive tests of the same name\nthe previous tests are removed and further tests of the same name will replace each other.\n\n```js\nlet max = 64;\nlet schema = yup.string().test({\n  name: 'max',\n  exclusive: true,\n  params: { max },\n  message: '${path} must be less than ${max} characters',\n  test: (value) => value == null || value.length \u003C= max,\n});\n```\n\n#### `Schema.transform((currentValue: any, originalValue: any, schema: Schema,  options: object) => any): Schema`\n\nAdds a transformation to the transform chain. Transformations are central to the casting process,\ndefault transforms for each type coerce values to the specific type (as verified by [`isType()`](#schemaistypevalue-any-value-is-infertypeschema)). transforms are run before validations and only applied when the schema is not marked as `strict` (the default). Some types have built in transformations.\n\nTransformations are useful for arbitrarily altering how the object is cast, **however, you should take care\nnot to mutate the passed in value.** Transforms are run sequentially so each `value` represents the\ncurrent state of the cast, you can use the `originalValue` param if you need to work on the raw initial value.\n\n```js\nlet schema = string().transform((value, originalValue) => {\n  return this.isType(value) && value !== null ? value.toUpperCase() : value;\n});\n\nschema.cast('jimmy'); \u002F\u002F => 'JIMMY'\n```\n\nEach types will handle basic coercion of values to the proper type for you, but occasionally\nyou may want to adjust or refine the default behavior. For example, if you wanted to use a different\ndate parsing strategy than the default one you could do that with a transform.\n\n```js\nmodule.exports = function (formats = 'MMM dd, yyyy') {\n  return date().transform((value, originalValue, context) => {\n    \u002F\u002F check to see if the previous transform already parsed the date\n    if (context.isType(value)) return value;\n\n    \u002F\u002F the default coercion failed so let's try it with Moment.js instead\n    value = Moment(originalValue, formats);\n\n    \u002F\u002F if it's valid return the date object, otherwise return an `InvalidDate`\n    return value.isValid() ? value.toDate() : new Date('');\n  });\n};\n```\n\n### mixed\n\nCreates a schema that matches all types, or just the ones you configure. Inherits from [`Schema`](#Schema).\nMixed types extends `{}` by default instead of `any` or `unknown`. This is because in TypeScript `{}` means\nanything that isn't `null` or `undefined` which yup treats distinctly.\n\n```ts\nimport { mixed, InferType } from 'yup';\n\nlet schema = mixed().nullable();\n\nschema.validateSync('string'); \u002F\u002F 'string';\n\nschema.validateSync(1); \u002F\u002F 1;\n\nschema.validateSync(new Date()); \u002F\u002F Date;\n\nInferType\u003Ctypeof schema>; \u002F\u002F {} | undefined\n\nInferType\u003Ctypeof schema.nullable().defined()>; \u002F\u002F {} | null\n```\n\nCustom types can be implemented by passing a type `check` function. This will also\nnarrow the TypeScript type for the schema.\n\n```ts\nimport { mixed, InferType } from 'yup';\n\nlet objectIdSchema = yup\n  .mixed((input): input is ObjectId => input instanceof ObjectId)\n  .transform((value: any, input, ctx) => {\n    if (ctx.isType(value)) return value;\n    return new ObjectId(value);\n  });\n\nawait objectIdSchema.validate(ObjectId('507f1f77bcf86cd799439011')); \u002F\u002F ObjectId(\"507f1f77bcf86cd799439011\")\n\nawait objectIdSchema.validate('507f1f77bcf86cd799439011'); \u002F\u002F ObjectId(\"507f1f77bcf86cd799439011\")\n\nInferType\u003Ctypeof objectIdSchema>; \u002F\u002F ObjectId\n```\n\n### string\n\nDefine a string schema. Inherits from [`Schema`](#Schema).\n\n```js\nlet schema = yup.string();\n\nawait schema.isValid('hello'); \u002F\u002F => true\n```\n\nBy default, the `cast` logic of `string` is to call `toString` on the value if it exists.\n\nempty values are not coerced (use `ensure()` to coerce empty values to empty strings).\n\nFailed casts return the input value.\n\n#### `string.required(message?: string | function): Schema`\n\nThe same as the `mixed()` schema required, **except** that empty strings are also considered 'missing' values.\n\n#### `string.length(limit: number | Ref, message?: string | function): Schema`\n\nSet a required length for the string value. The `${length}` interpolation can be used in the `message` argument\n\n#### `string.min(limit: number | Ref, message?: string | function): Schema`\n\nSet a minimum length limit for the string value. The `${min}` interpolation can be used in the `message` argument\n\n#### `string.max(limit: number | Ref, message?: string | function): Schema`\n\nSet a maximum length limit for the string value. The `${max}` interpolation can be used in the `message` argument\n\n#### `string.matches(regex: Regex, message?: string | function): Schema`\n\nProvide an arbitrary `regex` to match the value against.\n\n```js\nlet schema = string().matches(\u002F(hi|bye)\u002F);\n\nawait schema.isValid('hi'); \u002F\u002F => true\nawait schema.isValid('nope'); \u002F\u002F => false\n```\n\n#### `string.matches(regex: Regex, options: { message: string, excludeEmptyString: bool }): Schema`\n\nAn alternate signature for `string.matches` with an options object. `excludeEmptyString`, when true,\nshort circuits the regex test when the value is an empty string, making it a easier to avoid\nmatching nothing without complicating the regex.\n\n```js\nlet schema = string().matches(\u002F(hi|bye)\u002F, { excludeEmptyString: true });\n\nawait schema.isValid(''); \u002F\u002F => true\n```\n\n#### `string.email(message?: string | function): Schema`\n\nValidates the value as an email address using the same regex as defined by the HTML spec.\n\nWATCH OUT: Validating email addresses is nearly impossible with just code. Different\nclients and servers accept different things and many diverge from the various specs defining\n\"valid\" emails. The ONLY real way to validate an email address is to send a verification email\nto it and check that the user got it. With that in mind, yup picks a relatively simple regex\nthat does not cover all cases, but aligns with browser input validation behavior since HTML\nforms are a common use case for yup.\n\nIf you have more specific needs please override the email method with your own logic or regex:\n\n```ts\nyup.addMethod(yup.string, 'email', function validateEmail(message) {\n  return this.matches(myEmailRegex, {\n    message,\n    name: 'email',\n    excludeEmptyString: true,\n  });\n});\n```\n\n#### `string.url(message?: string | function): Schema`\n\nValidates the value as a valid URL via a regex.\n\n#### `string.uuid(message?: string | function): Schema`\n\nValidates the value as a valid UUID via a regex.\n\n#### `string.datetime(options?: {message?: string | function, allowOffset?: boolean, precision?: number})`\n\nValidates the value as an ISO datetime via a regex. Defaults to UTC validation; timezone offsets are not permitted (see `options.allowOffset`).\n\nUnlike `.date()`, `datetime` will not convert the string to a `Date` object. `datetime` also provides greater customization over the required format of the datetime string than `date` does.\n\n`options.allowOffset`: Allow a time zone offset. False requires UTC 'Z' timezone. _(default: false)_\n`options.precision`: Require a certain sub-second precision on the date. _(default: null -- any (or no) sub-second precision)_\n\n#### `string.datetime(message?: string | function)`\n\nAn alternate signature for `string.datetime` that can be used when you don't need to pass options other than `message`.\n\n#### `string.ensure(): Schema`\n\nTransforms `undefined` and `null` values to an empty string along with\nsetting the `default` to an empty string.\n\n#### `string.trim(message?: string | function): Schema`\n\nTransforms string values by removing leading and trailing whitespace. If\n`strict()` is set it will only validate that the value is trimmed.\n\n#### `string.lowercase(message?: string | function): Schema`\n\nTransforms the string value to lowercase. If `strict()` is set it\nwill only validate that the value is lowercase.\n\n#### `string.uppercase(message?: string | function): Schema`\n\nTransforms the string value to uppercase. If `strict()` is set it\nwill only validate that the value is uppercase.\n\n### number\n\nDefine a number schema. Inherits from [`Schema`](#Schema).\n\n```js\nlet schema = yup.number();\n\nawait schema.isValid(10); \u002F\u002F => true\n```\n\nThe default `cast` logic of `number` is: [`parseFloat`](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript\u002FReference\u002FGlobal_Objects\u002FparseFloat).\n\nFailed casts return `NaN`.\n\n#### `number.min(limit: number | Ref, message?: string | function): Schema`\n\nSet the minimum value allowed. The `${min}` interpolation can be used in the\n`message` argument.\n\n#### `number.max(limit: number | Ref, message?: string | function): Schema`\n\nSet the maximum value allowed. The `${max}` interpolation can be used in the\n`message` argument.\n\n#### `number.lessThan(max: number | Ref, message?: string | function): Schema`\n\nValue must be less than `max`. The `${less}` interpolation can be used in the\n`message` argument.\n\n#### `number.moreThan(min: number | Ref, message?: string | function): Schema`\n\nValue must be strictly greater than `min`. The `${more}` interpolation can be used in the\n`message` argument.\n\n#### `number.positive(message?: string | function): Schema`\n\nValue must be a positive number.\n\n#### `number.negative(message?: string | function): Schema`\n\nValue must be a negative number.\n\n#### `number.integer(message?: string | function): Schema`\n\nValidates that a number is an integer.\n\n#### `number.truncate(): Schema`\n\nTransformation that coerces the value to an integer by stripping off the digits\nto the right of the decimal point.\n\n#### `number.round(type: 'floor' | 'ceil' | 'trunc' | 'round' = 'round'): Schema`\n\nAdjusts the value via the specified method of `Math` (defaults to 'round').\n\n### boolean\n\nDefine a boolean schema. Inherits from [`Schema`](#Schema).\n\n```js\nlet schema = yup.boolean();\n\nawait schema.isValid(true); \u002F\u002F => true\n```\n\n### date\n\nDefine a Date schema. By default ISO date strings will parse correctly,\nfor more robust parsing options see the extending schema types at the end of the readme.\nInherits from [`Schema`](#Schema).\n\n```js\nlet schema = yup.date();\n\nawait schema.isValid(new Date()); \u002F\u002F => true\n```\n\nThe default `cast` logic of `date` is pass the value to the `Date` constructor, failing that, it will attempt\nto parse the date as an ISO date string.\n\n> If you would like ISO strings to not be cast to a `Date` object, use `.datetime()` instead.\n\nFailed casts return an invalid Date.\n\n#### `date.min(limit: Date | string | Ref, message?: string | function): Schema`\n\nSet the minimum date allowed. When a string is provided it will attempt to cast to a date first\nand use the result as the limit.\n\n#### `date.max(limit: Date | string | Ref, message?: string | function): Schema`\n\nSet the maximum date allowed, When a string is provided it will attempt to cast to a date first\nand use the result as the limit.\n\n### array\n\nDefine an array schema. Arrays can be typed or not, When specifying the element type, `cast` and `isValid`\nwill apply to the elements as well. Options passed into `isValid` are also passed to child schemas.\n\nInherits from [`Schema`](#Schema).\n\n```js\nlet schema = yup.array().of(yup.number().min(2));\n\nawait schema.isValid([2, 3]); \u002F\u002F => true\nawait schema.isValid([1, -24]); \u002F\u002F => false\n\nschema.cast(['2', '3']); \u002F\u002F => [2, 3]\n```\n\nYou can also pass a subtype schema to the array constructor as a convenience.\n\n```js\narray().of(yup.number());\n\u002F\u002F or\narray(yup.number());\n```\n\nArrays have no default casting behavior.\n\n#### `array.of(type: Schema): this`\n\nSpecify the schema of array elements. `of()` is optional and when omitted the array schema will\nnot validate its contents.\n\n#### `array.json(): this`\n\nAttempt to parse input string values as JSON using [`JSON.parse`](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript\u002FReference\u002FGlobal_Objects\u002FJSON\u002Fparse).\n\n#### `array.length(length: number | Ref, message?: string | function): this`\n\nSet a specific length requirement for the array. The `${length}` interpolation can be used in the `message` argument.\n\n#### `array.min(limit: number | Ref, message?: string | function): this`\n\nSet a minimum length limit for the array. The `${min}` interpolation can be used in the `message` argument.\n\n#### `array.max(limit: number | Ref, message?: string | function): this`\n\nSet a maximum length limit for the array. The `${max}` interpolation can be used in the `message` argument.\n\n#### `array.ensure(): this`\n\nEnsures that the value is an array, by setting the default to `[]` and transforming `null` and `undefined`\nvalues to an empty array as well. Any non-empty, non-array value will be wrapped in an array.\n\n```js\narray().ensure().cast(null); \u002F\u002F => []\narray().ensure().cast(1); \u002F\u002F => [1]\narray().ensure().cast([1]); \u002F\u002F => [1]\n```\n\n#### `array.compact(rejector: (value) => boolean): Schema`\n\nRemoves falsey values from the array. Providing a rejecter function lets you specify the rejection criteria yourself.\n\n```js\narray().compact().cast(['', 1, 0, 4, false, null]); \u002F\u002F => [1, 4]\n\narray()\n  .compact(function (v) {\n    return v == null;\n  })\n  .cast(['', 1, 0, 4, false, null]); \u002F\u002F => ['', 1, 0, 4, false]\n```\n\n### tuple\n\nTuples, are fixed length arrays where each item has a distinct type.\n\nInherits from [`Schema`](#Schema).\n\n```js\nimport { tuple, string, number, InferType } from 'yup';\n\nlet schema = tuple([\n  string().label('name'),\n  number().label('age').positive().integer(),\n]);\n\nawait schema.validate(['James', 3]); \u002F\u002F ['James', 3]\n\nawait schema.validate(['James', -24]); \u002F\u002F => ValidationError: age must be a positive number\n\nInferType\u003Ctypeof schema> \u002F\u002F [string, number] | undefined\n```\n\ntuples have no default casting behavior.\n\n### object\n\nDefine an object schema. Options passed into `isValid` are also passed to child schemas.\nInherits from [`Schema`](#Schema).\n\n```js\nyup.object({\n  name: string().required(),\n  age: number().required().positive().integer(),\n  email: string().email(),\n  website: string().url(),\n});\n```\n\nobject schema do not have any default transforms applied.\n\n#### Object schema defaults\n\nObject schema come with a default value already set, which \"builds\" out the object shape, a\nsets any defaults for fields:\n\n```js\nlet schema = object({\n  name: string().default(''),\n});\n\nschema.default(); \u002F\u002F -> { name: '' }\n```\n\nThis may be a bit surprising, but is usually helpful since it allows large, nested\nschema to create default values that fill out the whole shape and not just the root object. There is\none gotcha! though. For nested object schema that are optional but include non optional fields\nmay fail in unexpected ways:\n\n```js\nlet schema = object({\n  id: string().required(),\n  names: object({\n    first: string().required(),\n  }),\n});\n\nschema.isValid({ id: 1 }); \u002F\u002F false! names.first is required\n```\n\nThis is because yup casts the input object before running validation\nwhich will produce:\n\n> `{ id: '1', names: { first: undefined }}`\n\nDuring the validation phase `names` exists, and is validated, finding `names.first` missing.\nIf you wish to avoid this behavior do one of the following:\n\n- Set the nested default to undefined: `names.default(undefined)`\n- mark it nullable and default to null: `names.nullable().default(null)`\n\n#### `object.shape(fields: object, noSortEdges?: Array\u003C[string, string]>): Schema`\n\nDefine the keys of the object and the schemas for said keys.\n\nNote that you can chain `shape` method, which acts like `Object.assign`.\n\n```ts\nobject({\n  a: string(),\n  b: number(),\n}).shape({\n  b: string(),\n  c: number(),\n});\n```\n\nwould be exactly the same as:\n\n```ts\nobject({\n  a: string(),\n  b: string(),\n  c: number(),\n});\n```\n\n#### `object.json(): this`\n\nAttempt to parse input string values as JSON using [`JSON.parse`](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript\u002FReference\u002FGlobal_Objects\u002FJSON\u002Fparse).\n\n#### `object.concat(schemaB: ObjectSchema): ObjectSchema`\n\nCreates a object schema, by applying all settings and fields from `schemaB` to the base, producing a new schema.\nThe object shape is shallowly merged with common fields from `schemaB` taking precedence over the base\nfields.\n\n#### `object.pick(keys: string[]): Schema`\n\nCreate a new schema from a subset of the original's fields.\n\n```js\nlet person = object({\n  age: number().default(30).required(),\n  name: string().default('pat').required(),\n  color: string().default('red').required(),\n});\n\nlet nameAndAge = person.pick(['name', 'age']);\nnameAndAge.getDefault(); \u002F\u002F => { age: 30, name: 'pat'}\n```\n\n#### `object.omit(keys: string[]): Schema`\n\nCreate a new schema with fields omitted.\n\n```js\nlet person = object({\n  age: number().default(30).required(),\n  name: string().default('pat').required(),\n  color: string().default('red').required(),\n});\n\nlet nameAndAge = person.omit(['color']);\nnameAndAge.getDefault(); \u002F\u002F => { age: 30, name: 'pat'}\n```\n\n#### `object.from(fromKey: string, toKey: string, alias: boolean = false): this`\n\nTransforms the specified key to a new key. If `alias` is `true` then the old key will be left.\n\n```js\nlet schema = object({\n  myProp: mixed(),\n  Other: mixed(),\n})\n  .from('prop', 'myProp')\n  .from('other', 'Other', true);\n\nschema.cast({ prop: 5, other: 6 }); \u002F\u002F => { myProp: 5, other: 6, Other: 6 }\n```\n\n#### `object.exact(message?: string | function): Schema`\n\nValidates that the object does not contain extra or unknown properties\n\n#### `object.stripUnknown(): Schema`\n\nThe same as `object().validate(value, { stripUnknown: true})`, but as a transform method. When set\nany unknown properties will be removed.\n\n#### `object.noUnknown(onlyKnownKeys: boolean = true, message?: string | function): Schema`\n\nValidate that the object value only contains keys specified in `shape`, pass `false` as the first\nargument to disable the check. Restricting keys to known, also enables `stripUnknown` option, when not in strict mode.\n\n> Watch Out!: this method performs a transform and a validation, which may produce unexpected results.\n> For more explicit behavior use `object().stripUnknown` and `object().exact()`\n\n#### `object.camelCase(): Schema`\n\nTransforms all object keys to camelCase\n\n#### `object.constantCase(): Schema`\n\nTransforms all object keys to CONSTANT_CASE.\n","Yup 是一个用于运行时值解析和验证的模式构建工具。它支持定义模式来转换值以匹配特定格式，或者断言现有值的结构。Yup 的核心功能包括简洁且表达力强的模式接口、强大的 TypeScript 支持、内置异步验证支持以及可扩展性。通过 Yup，可以轻松地为从简单到复杂的各种数据模型创建验证规则，并生成丰富的错误信息以便于调试。此外，Yup 与 Standard Schema 兼容，使得在客户端和服务端都能很好地进行验证。适用于需要对输入数据进行严格校验的应用场景，如表单验证、API 数据处理等。","2026-06-11 02:55:24","top_language"]