Baike.dev
All toolsTrendingOpen sourceNewsSubmit
Log in
< 返回工具列表
Y

yup

> 编程语言
开源

Dead simple Object schema validation

23.7K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

Dead simple Object schema validation

Yup

Yup 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.

You are viewing docs for the v1.0.0 of yup, pre-v1 docs are available: here

Killer Features:

  • Concise yet expressive schema interface, equipped to model simple to complex data models
  • Powerful TypeScript support. Infer static types from schema, or ensure schema correctly implement a type
  • Built-in async validation support. Model server-side and client-side validation equally well
  • Extensible: add your own type-safe methods and schema
  • Rich error details, make debugging a breeze
  • Compatible with Standard Schema

Getting Started

Schema are comprised of parsing actions (transforms) as well as assertions (tests) about the input value. Validate an input value to parse it and run the configured set of assertions. Chain together methods to build a schema.

import { object, string, number, date, InferType } from 'yup';

let userSchema = object({
  name: string().required(),
  age: number().required().positive().integer(),
  email: string().email(),
  website: string().url().nullable(),
  createdOn: date().default(() => new Date()),
});

// parse and assert validity
let user = await userSchema.validate(await fetchUser());

type User = InferType<typeof userSchema>;
/* {
  name: string;
  age: number;
  email?: string | undefined
  website?: string | null | undefined
  createdOn: Date
}*/

Use a schema to coerce or "cast" an input value into the correct type, and optionally transform that value into more concrete and specific values, without making further assertions.

// Attempts to coerce values to the correct type
let parsedUser = userSchema.cast({
  name: 'jimmy',
  age: '24',
  createdOn: '2014-09-23T19:25:25Z',
});
// ✅  { name: 'jimmy', age: 24, createdOn: Date }

Know that your input value is already parsed? You can "strictly" validate an input, and avoid the overhead of running parsing logic.

// ❌  ValidationError "age is not a number"
let parsedUser = await userSchema.validate(
  {
    name: 'jimmy',
    age: '24',
  },
  { strict: true },
);

Table of Contents

  • Schema basics
    • Parsing: Transforms
    • Validation: Tests
      • Customizing errors
    • Composition and Reuse
  • TypeScript integration
    • Schema defaults
    • Ensuring a schema matches an existing type
    • Extending built-in schema with new methods
    • TypeScript configuration
  • Error message customization
    • localization and i18n
  • Standard Schema Support
  • API
    • yup
      • reach(schema: Schema, path: string, value?: object, context?: object): Schema
      • addMethod(schemaType: Schema, name: string, method: ()=> Schema): void
      • ref(path: string, options: { contextPrefix: string }): Ref
      • lazy((value: any) => Schema): Lazy
      • ValidationError(errors: string | Array<string>, value: any, path: string)
    • Schema
      • Schema.clone(): Schema
      • Schema.label(label: string): Schema
      • Schema.meta(metadata: SchemaMetadata): Schema
      • Schema.describe(options?: ResolveOptions): SchemaDescription
      • Schema.concat(schema: Schema): Schema
      • Schema.validate(value: any, options?: object): Promise<InferType<Schema>, ValidationError>
      • Schema.validateSync(value: any, options?: object): InferType<Schema>
      • Schema.validateAt(path: string, value: any, options?: object): Promise<InferType<Schema>, ValidationError>
      • Schema.validateSyncAt(path: string, value: any, options?: object): InferType<Schema>
      • Schema.isValid(value: any, options?: object): Promise<boolean>
      • Schema.isValidSync(value: any, options?: object): boolean
      • Schema.cast(value: any, options = {}): InferType<Schema>
      • Schema.isType(value: any): value is InferType<Schema>
      • Schema.strict(enabled: boolean = false): Schema
      • Schema.strip(enabled: boolean = true): Schema
      • Schema.withMutation(builder: (current: Schema) => void): void
      • Schema.default(value: any): Schema
      • Schema.getDefault(options?: object): Any
      • Schema.nullable(message?: string | function): Schema
      • Schema.nonNullable(message?: string | function): Schema
      • Schema.defined(): Schema
      • Schema.optional(): Schema
      • Schema.required(message?: string | function): Schema
      • Schema.notRequired(): Schema
      • Schema.typeError(message: string): Schema
      • Schema.oneOf(arrayOfValues: Array<any>, message?: string | function): Schema Alias: equals
      • Schema.notOneOf(arrayOfValues: Array<any>, message?: string | function)
      • Schema.when(keys: string | string[], builder: object | (values: any[], schema) => Schema): Schema
      • Schema.test(name: string, message: string | function | any, test: function): Schema
      • Schema.test(options: object): Schema
      • Schema.transform((currentValue: any, originalValue: any, schema: Schema, options: object) => any): Schema
    • mixed
    • string
      • string.required(message?: string | function): Schema
      • string.length(limit: number | Ref, message?: string | function): Schema
      • string.min(limit: number | Ref, message?: string | function): Schema
      • string.max(limit: number | Ref, message?: string | function): Schema
      • string.matches(regex: Regex, message?: string | function): Schema
      • string.matches(regex: Regex, options: { message: string, excludeEmptyString: bool }): Schema
      • string.email(message?: string | function): Schema
      • string.url(message?: string | function): Schema
      • string.uuid(message?: string | function): Schema
      • string.datetime(options?: {message?: string | function, allowOffset?: boolean, precision?: number})
      • string.datetime(message?: string | function)
      • string.ensure(): Schema
      • string.trim(message?: string | function): Schema
      • string.lowercase(message?: string | function): Schema
      • string.uppercase(message?: string | function): Schema
    • number
      • number.min(limit: number | Ref, message?: string | function): Schema
      • number.max(limit: number | Ref, message?: string | function): Schema
      • number.lessThan(max: number | Ref, message?: string | function): Schema
      • number.moreThan(min: number | Ref, message?: string | function): Schema
      • number.positive(message?: string | function): Schema
      • number.negative(message?: string | function): Schema
      • number.integer(message?: string | function): Schema
      • number.truncate(): Schema
      • number.round(type: 'floor' | 'ceil' | 'trunc' | 'round' = 'round'): Schema
    • boolean
    • date
      • date.min(limit: Date | string | Ref, message?: string | function): Schema
      • date.max(limit: Date | string | Ref, message?: string | function): Schema
    • array
      • array.of(type: Schema): this
      • array.json(): this
      • array.length(length: number | Ref, message?: string | function): this
      • array.min(limit: number | Ref, message?: string | function): this
      • array.max(limit: number | Ref, message?: string | function): this
      • array.ensure(): this
      • array.compact(rejector: (value) => boolean): Schema
    • tuple
    • object
      • Object schema defaults
      • object.shape(fields: object, noSortEdges?: Array<[string, string]>): Schema
      • object.json(): this
      • [object.concat(schemaB: ObjectSchema): ObjectSchema](#objectconcatschema

核心特点

  • •Concise yet expressive schema interface, equipped to model simple to complex data models
  • •Powerful TypeScript support. Infer static types from schema, or ensure schema correctly implement a type
  • •Built-in async validation support. Model server-side and client-side validation equally well
  • •Extensible: add your own type-safe methods and schema
  • •Rich error details, make debugging a breeze
  • •Compatible with Standard Schema
  • •Schema basics
  • •Parsing: Transforms
  • •Validation: Tests
  • •Customizing errors

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言