比特派钱包app安卓下载最新版本|yup

作者: 比特派钱包app安卓下载最新版本
2024-03-07 22:17:59

百度知道 - 信息提示

百度知道 - 信息提示

百度首页

商城

注册

登录

网页

资讯

视频

图片

知道

文库

贴吧采购

地图更多

搜索答案

我要提问

百度知道>提示信息

知道宝贝找不到问题了>_

该问题可能已经失效。返回首页

15秒以后自动返回

帮助

 | 意见反馈

 | 投诉举报

京ICP证030173号-1   京网文【2023】1034-029号     ©2024Baidu  使用百度前必读 | 知道协议 

单词 yup 和 yes 的使用辨析 - 知乎

单词 yup 和 yes 的使用辨析 - 知乎首发于百科知识切换模式写文章登录/注册单词 yup 和 yes 的使用辨析JerryWang​​思爱普(中国)有限公司成都分公司 开发专家当谈到英语中的“yup”时,它通常被认为是一个非正式的、口语化的肯定回答,相当于“是的”或“对的”。这个词汇主要在美国和加拿大的口语中使用较多,但在其他英语为母语的国家也可以听到。“yup”和“yes”之间的区别: 虽然“yup”和“yes”都表示同意或肯定,但它们之间有一些区别,主要在于语气和形式上:语气:“yup”通常被认为是更加非正式和轻松的表达方式。它常常用于与朋友、家人或非正式场合的对话中,以示亲近和友好。 “yes”则更加正式,通常在正式场合、商务交流或需要表达正式态度的情况下使用。 形式: “yup”是一个缩略形式,表示“yes”或“yeah”的口语化变体。“yes”是正式的、完整的单词。下面我将通过一些例子来详细说明这两个词汇的用法和区别:使用“yup”的例子:非正式对话:A: 你要来参加晚餐吗? B: Yup,我会来的。 朋友之间的聊天: A: 明天我们一起去看电影吗? B: 好的,yup,我很想去。 肯定回答问题: A: 你确定你已经做完了作业吗? B: Yup,都做完了。 回答简单问题: A: 你喜欢巧克力吗?B: Yup,我很喜欢。使用“yes”的例子:正式场合:A: 请确认您的身份。 B: Yes,我是John Smith。 商务交流: A: 你同意这份合同吗? B: Yes,我同意所有条款。 书面文件: 正式书信:Dear Sir/Madam, I am writing to inform you that I have received your letter, and I am pleased to confirm my attendance at the upcoming meeting on October 10th. Yes, I will be there. 需要强调正式性的情况: A: 你能否在明天早上9点参加会议?B: Yes,我会在明天早上9点准时出席会议。总之,虽然“yup”和“yes”都可以用于肯定回答,但它们的使用取决于上下文和所处的场合。如果你想表达一种轻松、非正式的语气,可以使用“yup”。但在正式场合或需要强调正式性的情况下,最好使用“yes”。无论哪个词汇,都是用来回答肯定的问题的,只是在语气和正式性上存在一些差异。在选择时,应根据具体情况和交流对象来做出合适的选择。发布于 2023-09-26 15:38・IP 属地四川单词辨析英语学习单词​赞同 2​​添加评论​分享​喜欢​收藏​申请转载​文章被以下专栏收录百科知识百

YUP中文(简体)翻译:剑桥词典

YUP中文(简体)翻译:剑桥词典

词典

翻译

语法

同义词词典

+Plus

剑桥词典+Plus

Shop

剑桥词典+Plus

我的主页

+Plus 帮助

退出

剑桥词典+Plus

我的主页

+Plus 帮助

退出

登录

/

注册

中文 (简体)

查找

查找

英语-中文(简体)

yup 在英语-中文(简体)词典中的翻译

yupadverb

  informal uk

Your browser doesn't support HTML5 audio

/jʌp/ us

Your browser doesn't support HTML5 audio

/jʌp/

Add to word list

Add to word list

(spelled the way it is spoken) yes

(口语)是,对

"Can you see it?" "Yup, there it is."

“你看得见吗?”“是,在那里呢。”

(yup在剑桥英语-中文(简体)词典的翻译 © Cambridge University Press)

yup的例句

yup

Yup, it's wrong, but it's understandable!

来自 Wikipedia

该例句来自维基百科,在CC BY-SA许可下可重复使用。

Yup, he's coming to check me out.

来自 Wikipedia

该例句来自维基百科,在CC BY-SA许可下可重复使用。

示例中的观点不代表剑桥词典编辑、剑桥大学出版社和其许可证颁发者的观点。

C1

yup的翻译

中文(繁体)

(口語)是,對…

查看更多内容

西班牙语

sí…

查看更多内容

需要一个翻译器吗?

获得快速、免费的翻译!

翻译器工具

yup的发音是什么?

在英语词典中查看 yup 的释义

浏览

Yuletide

yum

yummy

yummy mummy

yup

yuppie

yuppify

yurt

yute

“每日一词”

veggie burger

UK

Your browser doesn't support HTML5 audio

/ˈvedʒ.i ˌbɜː.ɡər/

US

Your browser doesn't support HTML5 audio

/ˈvedʒ.i ˌbɝː.ɡɚ/

a type of food similar to a hamburger but made without meat, by pressing together small pieces of vegetables, seeds, etc. into a flat, round shape

关于这个

博客

Forget doing it or forget to do it? Avoiding common mistakes with verb patterns (2)

March 06, 2024

查看更多

新词

stochastic parrot

March 04, 2024

查看更多

已添加至 list

回到页面顶端

内容

英语-中文(简体)例句翻译

©剑桥大学出版社与评估2024

学习

学习

学习

新词

帮助

纸质书出版

Word of the Year 2021

Word of the Year 2022

Word of the Year 2023

开发

开发

开发

词典API

双击查看

搜索Widgets

执照数据

关于

关于

关于

无障碍阅读

剑桥英语教学

剑桥大学出版社与评估

授权管理

Cookies与隐私保护

语料库

使用条款

京ICP备14002226号-2

©剑桥大学出版社与评估2024

剑桥词典+Plus

我的主页

+Plus 帮助

退出

词典

定义

清晰解释自然的书面和口头英语

英语

学习词典

基础英式英语

基础美式英语

翻译

点击箭头改变翻译方向。

双语词典

英语-中文(简体)

Chinese (Simplified)–English

英语-中文(繁体)

Chinese (Traditional)–English

英语-荷兰语

荷兰语-英语

英语-法语

法语-英语

英语-德语

德语-英语

英语-印尼语

印尼语-英语

英语-意大利语

意大利语-英语

英语-日语

日语-英语

英语-挪威语

挪威语-英语

英语-波兰语

波兰语-英语

英语-葡萄牙语

葡萄牙语-英语

英语-西班牙语

西班牙语-英语

English–Swedish

Swedish–English

半双语词典

英语-阿拉伯语

英语-孟加拉语

英语-加泰罗尼亚语

英语-捷克语

英语-丹麦语

English–Gujarati

英语-印地语

英语-韩语

英语-马来语

英语-马拉地语

英语-俄语

English–Tamil

English–Telugu

英语-泰语

英语-土耳其语

英语-乌克兰语

English–Urdu

英语-越南语

翻译

语法

同义词词典

Pronunciation

剑桥词典+Plus

Shop

剑桥词典+Plus

我的主页

+Plus 帮助

退出

登录 /

注册

中文 (简体)  

Change

English (UK)

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

中文 (简体)

正體中文 (繁體)

Polski

한국어

Türkçe

日本語

Tiếng Việt

हिंदी

தமிழ்

తెలుగు

关注我们

选择一本词典

最近的词和建议

定义

清晰解释自然的书面和口头英语

英语

学习词典

基础英式英语

基础美式英语

语法与同义词词典

对自然书面和口头英语用法的解释

英语语法

同义词词典

Pronunciation

British and American pronunciations with audio

English Pronunciation

翻译

点击箭头改变翻译方向。

双语词典

英语-中文(简体)

Chinese (Simplified)–English

英语-中文(繁体)

Chinese (Traditional)–English

英语-荷兰语

荷兰语-英语

英语-法语

法语-英语

英语-德语

德语-英语

英语-印尼语

印尼语-英语

英语-意大利语

意大利语-英语

英语-日语

日语-英语

英语-挪威语

挪威语-英语

英语-波兰语

波兰语-英语

英语-葡萄牙语

葡萄牙语-英语

英语-西班牙语

西班牙语-英语

English–Swedish

Swedish–English

半双语词典

英语-阿拉伯语

英语-孟加拉语

英语-加泰罗尼亚语

英语-捷克语

英语-丹麦语

English–Gujarati

英语-印地语

英语-韩语

英语-马来语

英语-马拉地语

英语-俄语

English–Tamil

English–Telugu

英语-泰语

英语-土耳其语

英语-乌克兰语

English–Urdu

英语-越南语

词典+Plus

词汇表

选择语言

中文 (简体)  

English (UK)

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

正體中文 (繁體)

Polski

한국어

Türkçe

日本語

Tiếng Việt

हिंदी

தமிழ்

తెలుగు

内容

英语-中文(简体) 

 Adverb

例句

Translations

语法

所有翻译

我的词汇表

把yup添加到下面的一个词汇表中,或者创建一个新词汇表。

更多词汇表

前往词汇表

对该例句有想法吗?

例句中的单词与输入词条不匹配。

该例句含有令人反感的内容。

取消

提交

例句中的单词与输入词条不匹配。

该例句含有令人反感的内容。

取消

提交

yup 入门 - 知乎

yup 入门 - 知乎首发于花田里说切换模式写文章登录/注册yup 入门花萼横江ps:中秋节了,放个月饼不过分吧。Photo by Macau Photo Agency on Unsplashyup是一个 javascript lib,用于数据 validation 和 parse。下面是一个简单的例子:yup.string().min(2).max(20).required()

上面的代码定义一个字符串schema,要求长度范围 2 - 20,且不能为 null。定义好schema之后,可以调用 validate 方法以验证输入,得到验证结果,如果验证失败,会返回一个 validationError。yup.string().min(2).max(20).required().validate('')或者调用 cast 方法将输入转化为符合 schema 的结果。yup.string().min(2).max(20).required().cast(1)如果输入类型与schema预期的类型不一致,会尝试转型,比如,数字 1 会转化为字符串 "1",date 对象会调用 toString 方法转化为字符串。这就是 yup 的使用方法:定义 schema,使用 schema。那么,该如何理解 schema 呢?什么是 schema ? schema 是对数据的一种描述,yup.string() 描述数据是字符串类型。我们可以调用 required,min,max 等修饰方法来添加更多的修饰,也可以使用 test 方法来订制复杂的描述(test 比较复杂,会单独写一下)。除了 string,yup 还内置了 number,boolean,data,array,object schema。也可以通过 mixed 方法订制 schema。建立好 schema 之后,就可以使用它来验证数据是否符合描述。如果不符合,对应的错误信息就会返回。yup 内置了英文版本的错误信息,如果想定制为其他语言,有两种办法:全局或者局部。订制错误信息全局方式需要调用 setLocale 方法,可以在yup.setLocale({

number: {

min: '长度最少为 ${min}',

},

});${min} 的目的是访问调用 min 的参数,如 yup.string().min(2)错误信息也可以接受一个函数yup.setLocale({

number: {

min: ({min}) => {

// your code

},

},

});局部订制一般是在具体的 schema 修饰方法里添加错误信息yup.string().min(2, '太长了')

同样,这里的错误信息也可以是一个函数。使用函数替代基本类型变量是 yup 的惯用方法,在某些场合,这很有用。依赖验证数据的 validation 有时候会依赖其他数据项的结果,对于简单地依赖,可以使用 when (相对复杂的就要用 test 了)。object({

isBig: yup.boolean(),

count: yup.number()

.when('isBig', {

is: true, // alternatively: (val) => val == true

then: yup.number().min(5),

otherwise: yup.number().min(0),

})

});

上面的 when 监测 isBig 数据,is 定义监测指标,这里的指标是 true。当 isBig 的值符合 is 时,使用 then 代表的 schema,否则使用 otherwise schema。when 也可以依赖多个数据yup.object({

isSpecial: yup.boolean(),

isBig: yup.boolean(),

count: yup.number().when(['isBig', 'isSpecial'], {

is: true, // 相当于: (isBig, isSpecial) => isBig && isSpecial

then: yup.number().min(5),

otherwise: yup.number().min(0),

}),

});也可以不使用 is/then/otherwise 结构,直接返回一个 schema。yup.object({

isBig: yup.boolean(),

count: yup.number().when('isBig', (isBig, schema) => {

return isBig ? schema.min(5) : schema.min(0);

}),

})我个人更喜欢用 function 来描述复合逻辑,相比 is/then/otherwise 这种二元分支,function可以做到更多。使用 ref 做依赖验证ref 是 yup 对数据项的一个引用,可以在各种描述方法中使用 ref 来设置依赖。yup.object({

limit: yup.number().min(1).required(),

total: yup.number().min(yup.ref('limit'))

})total 的 min 值取自于 limit 的值,当 limit 的值发生变化,total 的min 限制也会对应改变。ref 风格依赖验证的不足之处是只能一对一,无法描述更复杂的关系。最后稍微了解一下 mixed什么是 mixed?mixed 是所有内置 schema 的基类,mixed 上定义的方法在其他 schema 上可用。所以,如果内置 schema 不能满足要求,我们也可以通过 mixed 订制自己的 schema。这和 yup 内部建立基本 schema 的方式是一样的。为什么推荐 yup?我在去年接触 formik 之后了解到 yup - 作为一个强力的 form validation tool。在那之前,我用过各种 form validation,大致可以分为两类:lineline 声明,外置声明。我个人比较偏好第二种,因为有利于精细控制,以及拆分复用。yup 就是第二种中的佼佼者,而且恰好契合我的审美。所以一直在使用。对于 inline 声明的不足之处,除了不利于精细控制,和拆分复用之外,另一个问题是,不同的 ui lib 在这方面的差异会导致额外的学习负担。而精通 yup 则可以处处使用。当然,在这个意义上说,学习其他优秀的 validation tool 也未尝不可。如果 yup 的什么不符合你的要求,大可以寻觅其他替代品。发布于 2020-09-25 17:15验证表单​赞同 13​​1 条评论​分享​喜欢​收藏​申请转载​文章被以下专栏收录花田里说花萼横江

yup - npm

yup - npm

skip to:contentpackage searchsign in❤Nine Pedestrians MesmerizedProTeamsPricingDocumentationnpmSearchSign UpSign In yup1.4.0 • Public • Published a day ago ReadmeCode Beta4 Dependencies5,400 Dependents127 VersionsYup

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

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

const user = await userSchema.validate(await fetchUser());

type User = InferType;

/* {

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

const 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"

const 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

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, 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, ValidationError>

Schema.validateSync(value: any, options?: object): InferType

Schema.validateAt(path: string, value: any, options?: object): Promise, ValidationError>

Schema.validateSyncAt(path: string, value: any, options?: object): InferType

Schema.isValid(value: any, options?: object): Promise

Schema.isValidSync(value: any, options?: object): boolean

Schema.cast(value: any, options = {}): InferType

Schema.isType(value: any): value is InferType

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, message?: string | function): Schema Alias: equals

Schema.notOneOf(arrayOfValues: Array, 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) => 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

object.pick(keys: string[]): Schema

object.omit(keys: string[]): Schema

object.from(fromKey: string, toKey: string, alias: boolean = false): this

object.noUnknown(onlyKnownKeys: boolean = true, message?: string | function): Schema

object.camelCase(): Schema

object.constantCase(): Schema

Schema basics

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

In order to be maximally flexible yup allows running both parsing and assertions separately to match specific needs

Parsing: Transforms

Each built-in type implements basic type parsing, which comes in handy when parsing serialized data, such as JSON.

Additionally types implement type specific transforms that can be enabled.

const num = number().cast('1'); // 1

const obj = object({

firstName: string().lowercase().trim(),

})

.json()

.camelCase()

.cast('{"first_name": "jAnE "}'); // { firstName: 'jane' }

Custom transforms can be added

const reversedString = string()

.transform((currentValue) => currentValue.split('').reverse().join(''))

.cast('dlrow olleh'); // "hello world"

Transforms form a "pipeline", where the value of a previous transform is piped into the next one.

When an input value is undefined yup will apply the schema default if it's configured.

Watch out! values are not guaranteed to be valid types in transform functions. Previous transforms

may have failed. For example a number transform may be receive the input value, NaN, or a number.

Validation: Tests

Yup schema run "tests" over input values. Tests assert that inputs conform to some

criteria. Tests are distinct from transforms, in that they do not change or alter the input (or its type)

and are usually reserved for checks that are hard, if not impossible, to represent in static types.

string()

.min(3, 'must be at least 3 characters long')

.email('must be a valid email')

.validate('no'); // ValidationError

As with transforms, tests can be customized on the fly

const jamesSchema = string().test(

'is-james',

(d) => `${d.path} is not James`,

(value) => value == null || value === 'James',

);

jamesSchema.validateSync('James'); // "James"

jamesSchema.validateSync('Jane'); // ValidationError "this is not James"

Heads up: unlike transforms, value in a custom test is guaranteed to be the correct type

(in this case an optional string). It still may be undefined or null depending on your schema

in those cases, you may want to return true for absent values unless your transform makes presence

related assertions. The test option skipAbsent will do this for you if set.

Customizing errors

In the simplest case a test function returns true or false depending on the whether the check

passed. In the case of a failing test, yup will throw

a ValidationError with your (or the default)

message for that test. ValidationErrors also contain a bunch of other metadata about the test,

including it's name, what arguments (if any) it was called with, and the path to the failing field

in the case of a nested validation.

Error messages can also be constructed on the fly to customize how the schema fails.

const order = object({

no: number().required().

sku: string().test({

name: 'is-sku',

skipAbsent: true,

test(value, ctx) {

if (!value.startsWith('s-')) {

return ctx.createError({ message: 'SKU missing correct prefix' })

}

if (!value.endsWith('-42a')) {

return ctx.createError({ message: 'SKU missing correct suffix' })

}

if (value.length < 10) {

return ctx.createError({ message: 'SKU is not the right length' })

}

return true

}

})

})

order.validate({ no: 1234, sku: 's-1a45-14a' })

Composition and Reuse

Schema are immutable, each method call returns a new schema object. Reuse and pass them around without

fear of mutating another instance.

const optionalString = string().optional();

const definedString = optionalString.defined();

const value = undefined;

optionalString.isValid(value); // true

definedString.isValid(value); // false

TypeScript integration

Yup schema produce static TypeScript interfaces. Use InferType to extract that interface:

import * as yup from 'yup';

const personSchema = yup.object({

firstName: yup.string().defined(),

nickName: yup.string().default('').nullable(),

sex: yup

.mixed()

.oneOf(['male', 'female', 'other'] as const)

.defined(),

email: yup.string().nullable().email(),

birthDate: yup.date().nullable().min(new Date(1900, 0, 1)),

});

interface Person extends yup.InferType {

// using interface instead of type generally gives nicer editor feedback

}

Schema defaults

A schema's default is used when casting produces an undefined output value. Because of this,

setting a default affects the output type of the schema, essentially marking it as "defined()".

import { string } from 'yup';

const value: string = string().default('hi').validate(undefined);

// vs

const value: string | undefined = string().validate(undefined);

Ensuring a schema matches an existing type

In some cases a TypeScript type already exists, and you want to ensure that

your schema produces a compatible type:

import { object, number, string, ObjectSchema } from 'yup';

interface Person {

name: string;

age?: number;

sex: 'male' | 'female' | 'other' | null;

}

// will raise a compile-time type error if the schema does not produce a valid Person

const schema: ObjectSchema = object({

name: string().defined(),

age: number().optional(),

sex: string<'male' | 'female' | 'other'>().nullable().defined(),

});

// ❌ errors:

// "Type 'number | undefined' is not assignable to type 'string'."

const badSchema: ObjectSchema = object({

name: number(),

});

Extending built-in schema with new methods

You can use TypeScript's interface merging behavior to extend the schema types

if needed. Type extensions should go in an "ambient" type definition file such as your

globals.d.ts. Remember to actually extend the yup type in your application code!

Watch out! merging only works if the type definition is exactly the same, including

generics. Consult the yup source code for each type to ensure you are defining it correctly

// globals.d.ts

declare module 'yup' {

interface StringSchema {

append(appendStr: string): this;

}

}

// app.ts

import { addMethod, string } from 'yup';

addMethod(string, 'append', function append(appendStr: string) {

return this.transform((value) => `${value}${appendStr}`);

});

string().append('~~~~').cast('hi'); // 'hi~~~~'

TypeScript configuration

You must have the strictNullChecks compiler option enabled for type inference to work.

We also recommend settings strictFunctionTypes to false, for functionally better types. Yes

this reduces overall soundness, however TypeScript already disables this check

for methods and constructors (note from TS docs):

During development of this feature, we discovered a large number of inherently

unsafe class hierarchies, including some in the DOM. Because of this,

the setting only applies to functions written in function syntax, not to those in method syntax:

Your mileage will vary, but we've found that this check doesn't prevent many of

real bugs, while increasing the amount of onerous explicit type casting in apps.

Error message customization

Default error messages can be customized for when no message is provided with a validation test.

If any message is missing in the custom dictionary the error message will default to Yup's one.

import { setLocale } from 'yup';

setLocale({

mixed: {

default: 'Não é válido',

},

number: {

min: 'Deve ser maior que ${min}',

},

});

// now use Yup schemas AFTER you defined your custom dictionary

let schema = yup.object().shape({

name: yup.string(),

age: yup.number().min(18),

});

try {

await schema.validate({ name: 'jimmy', age: 11 });

} catch (err) {

err.name; // => 'ValidationError'

err.errors; // => ['Deve ser maior que 18']

}

localization and i18n

If you need multi-language support, yup has got you covered. The function setLocale accepts functions that can be used to

generate error objects with translation keys and values. These can be fed it into your favorite i18n library.

import { setLocale } from 'yup';

setLocale({

// use constant translation keys for messages without values

mixed: {

default: 'field_invalid',

},

// use functions to generate an error object that includes the value from the schema

number: {

min: ({ min }) => ({ key: 'field_too_short', values: { min } }),

max: ({ max }) => ({ key: 'field_too_big', values: { max } }),

},

});

// ...

let schema = yup.object().shape({

name: yup.string(),

age: yup.number().min(18),

});

try {

await schema.validate({ name: 'jimmy', age: 11 });

} catch (err) {

messages = err.errors.map((err) => i18next.t(err.key));

}

API

yup

The module export.

// core schema

import {

mixed,

string,

number,

boolean,

bool,

date,

object,

array,

ref,

lazy,

} from 'yup';

// Classes

import {

Schema,

MixedSchema,

StringSchema,

NumberSchema,

BooleanSchema,

DateSchema,

ArraySchema,

ObjectSchema,

} from 'yup';

// Types

import type { InferType, ISchema, AnySchema, AnyObjectSchema } from 'yup';

reach(schema: Schema, path: string, value?: object, context?: object): Schema

For nested schemas, reach will retrieve an inner schema based on the provided path.

For nested schemas that need to resolve dynamically, you can provide a value and optionally

a context object.

import { reach } from 'yup';

let schema = object({

nested: object({

arr: array(object({ num: number().max(4) })),

}),

});

reach(schema, 'nested.arr.num');

reach(schema, 'nested.arr[].num');

reach(schema, 'nested.arr[1].num');

reach(schema, 'nested["arr"][1].num');

addMethod(schemaType: Schema, name: string, method: ()=> Schema): void

Adds a new method to the core schema types. A friendlier convenience method for schemaType.prototype[name] = method.

import { addMethod, date } from 'yup';

addMethod(date, 'format', function format(formats, parseStrict) {

return this.transform((value, originalValue, ctx) => {

if (ctx.isType(value)) return value;

value = Moment(originalValue, formats, parseStrict);

return value.isValid() ? value.toDate() : new Date('');

});

});

If you want to add a method to ALL schema types, extend the abstract base class: Schema

import { addMethod, Schema } from 'yup';

addMethod(Schema, 'myMethod', ...)

ref(path: string, options: { contextPrefix: string }): Ref

Creates a reference to another sibling or sibling descendant field. Refs are resolved

at validation/cast time and supported where specified. Refs are evaluated in the proper order so that

the ref value is resolved before the field using the ref (be careful of circular dependencies!).

import { ref, object, string } from 'yup';

let schema = object({

baz: ref('foo.bar'),

foo: object({

bar: string(),

}),

x: ref('$x'),

});

schema.cast({ foo: { bar: 'boom' } }, { context: { x: 5 } });

// => { baz: 'boom', x: 5, foo: { bar: 'boom' } }

lazy((value: any) => Schema): Lazy

Creates a schema that is evaluated at validation/cast time. Useful for creating

recursive schema like Trees, for polymorphic fields and arrays.

CAUTION! When defining parent-child recursive object schema, you want to reset the default()

to null on the child—otherwise the object will infinitely nest itself when you cast it!

let node = object({

id: number(),

child: yup.lazy(() => node.default(undefined)),

});

let renderable = yup.lazy((value) => {

switch (typeof value) {

case 'number':

return number();

case 'string':

return string();

default:

return mixed();

}

});

let renderables = array().of(renderable);

ValidationError(errors: string | Array, value: any, path: string)

Thrown on failed validations, with the following properties

name: "ValidationError"

type: the specific test type or test "name", that failed.

value: The field value that was tested;

params?: The test inputs, such as max value, regex, etc;

path: a string, indicating where there error was thrown. path is empty at the root level.

errors: array of error messages

inner: in the case of aggregate errors, inner is an array of ValidationErrors throw earlier in the

validation chain. When the abortEarly option is false this is where you can inspect each error thrown,

alternatively, errors will have all of the messages from each inner error.

Schema

Schema is the abstract base class that all schema type inherit from. It provides a number of base methods and properties

to all other schema types.

Note: unless you are creating a custom schema type, Schema should never be used directly. For unknown/any types use mixed()

Schema.clone(): Schema

Creates a deep copy of the schema. Clone is used internally to return a new schema with every schema state change.

Schema.label(label: string): Schema

Overrides the key name which is used in error messages.

Schema.meta(metadata: SchemaMetadata): Schema

Adds to a metadata object, useful for storing data with a schema, that doesn't belong

to the cast object itself.

A custom SchemaMetadata interface can be defined through

merging

with the CustomSchemaMetadata interface. Start by creating a yup.d.ts file

in your package and creating your desired CustomSchemaMetadata interface:

// yup.d.ts

import 'yup';

declare module 'yup' {

// Define your desired `SchemaMetadata` interface by merging the

// `CustomSchemaMetadata` interface.

export interface CustomSchemaMetadata {

placeholderText?: string;

tooltipText?: string;

// …

}

}

Schema.describe(options?: ResolveOptions): SchemaDescription

Collects schema details (like meta, labels, and active tests) into a serializable

description object.

const schema = object({

name: string().required(),

});

const description = schema.describe();

For schema with dynamic components (references, lazy, or conditions), describe requires

more context to accurately return the schema description. In these cases provide options

import { ref, object, string, boolean } from 'yup';

let schema = object({

isBig: boolean(),

count: number().when('isBig', {

is: true,

then: (schema) => schema.min(5),

otherwise: (schema) => schema.min(0),

}),

});

schema.describe({ value: { isBig: true } });

And below are the description types, which differ a bit depending on the schema type.

interface SchemaDescription {

type: string;

label?: string;

meta: object | undefined;

oneOf: unknown[];

notOneOf: unknown[];

default?: unknown;

nullable: boolean;

optional: boolean;

tests: Array<{ name?: string; params: ExtraParams | undefined }>;

// Present on object schema descriptions

fields: Record;

// Present on array schema descriptions

innerType?: SchemaFieldDescription;

}

type SchemaFieldDescription =

| SchemaDescription

| SchemaRefDescription

| SchemaLazyDescription;

interface SchemaRefDescription {

type: 'ref';

key: string;

}

interface SchemaLazyDescription {

type: string;

label?: string;

meta: object | undefined;

}

Schema.concat(schema: Schema): Schema

Creates a new instance of the schema by combining two schemas. Only schemas of the same type can be concatenated.

concat is not a "merge" function in the sense that all settings from the provided schema, override ones in the

base, including type, presence and nullability.

mixed().defined().concat(mixed().nullable());

// produces the equivalent to:

mixed().defined().nullable();

Schema.validate(value: any, options?: object): Promise, ValidationError>

Returns 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

with a ValidationError.

value = await schema.validate({ name: 'jimmy', age: 24 });

Provide options to more specifically control the behavior of validate.

interface Options {

// when true, parsing is skipped and the input is validated "as-is"

strict: boolean = false;

// Throw on the first error or collect and return all

abortEarly: boolean = true;

// Remove unspecified keys from objects

stripUnknown: boolean = false;

// when `false` validations will be performed shallowly

recursive: boolean = true;

// External values that can be provided to validations and conditionals

context?: object;

}

Schema.validateSync(value: any, options?: object): InferType

Runs validatations synchronously if possible and returns the resulting value,

or throws a ValidationError. Accepts all the same options as validate.

Synchronous validation only works if there are no configured async tests, e.g tests that return a Promise.

For instance this will work:

let schema = number().test(

'is-42',

"this isn't the number i want",

(value) => value != 42,

);

schema.validateSync(23); // throws ValidationError

however this will not:

let schema = number().test('is-42', "this isn't the number i want", (value) =>

Promise.resolve(value != 42),

);

schema.validateSync(42); // throws Error

Schema.validateAt(path: string, value: any, options?: object): Promise, ValidationError>

Validate a deeply nested path within the schema. Similar to how reach works,

but uses the resulting schema as the subject for validation.

Note! The value here is the root value relative to the starting schema, not the value at the nested path.

let schema = object({

foo: array().of(

object({

loose: boolean(),

bar: string().when('loose', {

is: true,

otherwise: (schema) => schema.strict(),

}),

}),

),

});

let rootValue = {

foo: [{ bar: 1 }, { bar: 1, loose: true }],

};

await schema.validateAt('foo[0].bar', rootValue); // => ValidationError: must be a string

await schema.validateAt('foo[1].bar', rootValue); // => '1'

Schema.validateSyncAt(path: string, value: any, options?: object): InferType

Same as validateAt but synchronous.

Schema.isValid(value: any, options?: object): Promise

Returns true when the passed in value matches the schema. isValid

is asynchronous and returns a Promise object.

Takes the same options as validate().

Schema.isValidSync(value: any, options?: object): boolean

Synchronously returns true when the passed in value matches the schema.

Takes the same options as validateSync() and has the same caveats around async tests.

Schema.cast(value: any, options = {}): InferType

Attempts to coerce the passed in value to a value that matches the schema. For example: '5' will

cast to 5 when using the number() type. Failed casts generally return null, but may also

return results like NaN and unexpected strings.

Provide options to more specifically control the behavior of validate.

interface CastOptions {

// Remove undefined properties from objects

stripUnknown: boolean = false;

// Throws a TypeError if casting doesn't produce a valid type

// note that the TS return type is inaccurate when this is `false`, use with caution

assert?: boolean = true;

// External values that used to resolve conditions and references

context?: TContext;

}

Schema.isType(value: any): value is InferType

Runs a type check against the passed in value. It returns true if it matches,

it does not cast the value. When nullable() is set null is considered a valid value of the type.

You should use isType for all Schema type checks.

Schema.strict(enabled: boolean = false): Schema

Sets the strict option to true. Strict schemas skip coercion and transformation attempts,

validating the value "as is".

Schema.strip(enabled: boolean = true): Schema

Marks a schema to be removed from an output object. Only works as a nested schema.

let schema = object({

useThis: number(),

notThis: string().strip(),

});

schema.cast({ notThis: 'foo', useThis: 4 }); // => { useThis: 4 }

Schema with strip enabled have an inferred type of never, allowing them to be

removed from the overall type:

let schema = object({

useThis: number(),

notThis: string().strip(),

});

InferType; /*

{

useThis?: number | undefined

}

*/

Schema.withMutation(builder: (current: Schema) => void): void

First the legally required Rich Hickey quote:

If a tree falls in the woods, does it make a sound?

If a pure function mutates some local data in order to produce an immutable return value, is that ok?

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

declaration, and only happen once over the lifetime of the schema, so performance isn't an issue.

However certain mutations do occur at cast/validation time, (such as conditional schema using when()), or

when instantiating a schema object.

object()

.shape({ key: string() })

.withMutation((schema) => {

return arrayOfObjectTests.forEach((test) => {

schema.test(test);

});

});

Schema.default(value: any): Schema

Sets a default value to use when the value is undefined.

Defaults are created after transformations are executed, but before validations, to help ensure that safe

defaults are specified. The default value will be cloned on each use, which can incur performance penalty

for objects and arrays. To avoid this overhead you can also pass a function that returns a new default.

Note that null is considered a separate non-empty value.

yup.string.default('nothing');

yup.object.default({ number: 5 }); // object will be cloned every time a default is needed

yup.object.default(() => ({ number: 5 })); // this is cheaper

yup.date.default(() => new Date()); // also helpful for defaults that change over time

Schema.getDefault(options?: object): Any

Retrieve 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).

Schema.nullable(message?: string | function): Schema

Indicates that null is a valid value for the schema. Without nullable()

null is treated as a different type and will fail Schema.isType() checks.

const schema = number().nullable();

schema.cast(null); // null

InferType; // number | null

Schema.nonNullable(message?: string | function): Schema

The opposite of nullable, removes null from valid type values for the schema.

Schema are non nullable by default.

const schema = number().nonNullable();

schema.cast(null); // TypeError

InferType; // number

Schema.defined(): Schema

Require a value for the schema. All field values apart from undefined meet this requirement.

const schema = string().defined();

schema.cast(undefined); // TypeError

InferType; // string

Schema.optional(): Schema

The opposite of defined() allows undefined values for the given type.

const schema = string().optional();

schema.cast(undefined); // undefined

InferType; // string | undefined

Schema.required(message?: string | function): Schema

Mark the schema as required, which will not allow undefined or null as a value. required

negates the effects of calling optional() and nullable()

Watch out! string().required) works a little

different and additionally prevents empty string values ('') when required.

Schema.notRequired(): Schema

Mark the schema as not required. This is a shortcut for schema.nullable().optional();

Schema.typeError(message: string): Schema

Define an error message for failed type checks. The ${value} and ${type} interpolation can

be used in the message argument.

Schema.oneOf(arrayOfValues: Array, message?: string | function): Schema Alias: equals

Only allow values from set of values. Values added are removed from any notOneOf values if present.

The ${values} interpolation can be used in the message argument. If a ref or refs are provided,

the ${resolved} interpolation can be used in the message argument to get the resolved values that were checked

at validation time.

Note that undefined does not fail this validator, even when undefined is not included in arrayOfValues.

If you don't want undefined to be a valid value, you can use Schema.required.

let schema = yup.mixed().oneOf(['jimmy', 42]);

await schema.isValid(42); // => true

await schema.isValid('jimmy'); // => true

await schema.isValid(new Date()); // => false

Schema.notOneOf(arrayOfValues: Array, message?: string | function)

Disallow values from a set of values. Values added are removed from oneOf values if present.

The ${values} interpolation can be used in the message argument. If a ref or refs are provided,

the ${resolved} interpolation can be used in the message argument to get the resolved values that were checked

at validation time.

let schema = yup.mixed().notOneOf(['jimmy', 42]);

await schema.isValid(42); // => false

await schema.isValid(new Date()); // => true

Schema.when(keys: string | string[], builder: object | (values: any[], schema) => Schema): Schema

Adjust the schema based on a sibling or sibling children fields. You can provide an object

literal where the key is is value or a matcher function, then provides the true schema and/or

otherwise for the failure condition.

is conditions are strictly compared (===) if you want to use a different form of equality you

can provide a function like: is: (value) => value == true.

You can also prefix properties with $ to specify a property that is dependent

on context passed in by validate() or cast instead of the input value.

when conditions are additive.

then and otherwise are specified functions (schema: Schema) => Schema.

let schema = object({

isBig: boolean(),

count: number()

.when('isBig', {

is: true, // alternatively: (val) => val == true

then: (schema) => schema.min(5),

otherwise: (schema) => schema.min(0),

})

.when('$other', ([other], schema) =>

other === 4 ? schema.max(6) : schema,

),

});

await schema.validate(value, { context: { other: 4 } });

You can also specify more than one dependent key, in which case each value will be spread as an argument.

let schema = object({

isSpecial: boolean(),

isBig: boolean(),

count: number().when(['isBig', 'isSpecial'], {

is: true, // alternatively: (isBig, isSpecial) => isBig && isSpecial

then: (schema) => schema.min(5),

otherwise: (schema) => schema.min(0),

}),

});

await schema.validate({

isBig: true,

isSpecial: true,

count: 10,

});

Alternatively you can provide a function that returns a schema, called with an array of values for each provided key the current schema.

let schema = yup.object({

isBig: yup.boolean(),

count: yup.number().when('isBig', ([isBig], schema) => {

return isBig ? schema.min(5) : schema.min(0);

}),

});

await schema.validate({ isBig: false, count: 4 });

Schema.test(name: string, message: string | function | any, test: function): Schema

Adds a test function to the validation chain. Tests are run after any object is cast.

Many types have some tests built in, but you can create custom ones easily.

In order to allow asynchronous custom validations all (or no) tests are run asynchronously.

A consequence of this is that test execution order cannot be guaranteed.

All tests must provide a name, an error message and a validation function that must return

true when the current value is valid and false or a ValidationError otherwise.

To make a test async return a promise that resolves true or false or a ValidationError.

For the message argument you can provide a string which will interpolate certain values

if specified using the ${param} syntax. By default all test messages are passed a path value

which is valuable in nested schemas.

The test function is called with the current value. For more advanced validations you can

use the alternate signature to provide more options (see below):

let jimmySchema = string().test(

'is-jimmy',

'${path} is not Jimmy',

(value, context) => value === 'jimmy',

);

// or make it async by returning a promise

let asyncJimmySchema = string()

.label('First name')

.test(

'is-jimmy',

({ label }) => `${label} is not Jimmy`, // a message can also be a function

async (value, testContext) =>

(await fetch('/is-jimmy/' + value)).responseText === 'true',

);

await schema.isValid('jimmy'); // => true

await schema.isValid('john'); // => false

Test functions are called with a special context value, as the second argument, that exposes some useful metadata

and functions. For non arrow functions, the test context is also set as the function this. Watch out, if you access

it via this it won't work in an arrow function.

testContext.path: the string path of the current validation

testContext.schema: the resolved schema object that the test is running against.

testContext.options: the options object that validate() or isValid() was called with

testContext.parent: in the case of nested schema, this is the value of the parent object

testContext.originalValue: the original value that is being tested

testContext.createError(Object: { path: String, message: String, params: Object }): create and return a

validation error. Useful for dynamically setting the path, params, or more likely, the error message.

If either option is omitted it will use the current path, or default message.

Schema.test(options: object): Schema

Alternative test(..) signature. options is an object containing some of the following options:

Options = {

// unique name identifying the test

name: string;

// test function, determines schema validity

test: (value: any) => boolean;

// the validation error message

message: string;

// values passed to message for interpolation

params: ?object;

// mark the test as exclusive, meaning only one test of the same name can be active at once

exclusive: boolean = false;

}

In the case of mixing exclusive and non-exclusive tests the following logic is used.

If a non-exclusive test is added to a schema with an exclusive test of the same name

the exclusive test is removed and further tests of the same name will be stacked.

If an exclusive test is added to a schema with non-exclusive tests of the same name

the previous tests are removed and further tests of the same name will replace each other.

let max = 64;

let schema = yup.string().test({

name: 'max',

exclusive: true,

params: { max },

message: '${path} must be less than ${max} characters',

test: (value) => value == null || value.length <= max,

});

Schema.transform((currentValue: any, originalValue: any) => any): Schema

Adds a transformation to the transform chain. Transformations are central to the casting process,

default transforms for each type coerce values to the specific type (as verified by isType()). transforms are run before validations and only applied when the schema is not marked as strict (the default). Some types have built in transformations.

Transformations are useful for arbitrarily altering how the object is cast, however, you should take care

not to mutate the passed in value. Transforms are run sequentially so each value represents the

current state of the cast, you can use the originalValue param if you need to work on the raw initial value.

let schema = string().transform((value, originalValue) => {

return this.isType(value) && value !== null ? value.toUpperCase() : value;

});

schema.cast('jimmy'); // => 'JIMMY'

Each types will handle basic coercion of values to the proper type for you, but occasionally

you may want to adjust or refine the default behavior. For example, if you wanted to use a different

date parsing strategy than the default one you could do that with a transform.

module.exports = function (formats = 'MMM dd, yyyy') {

return date().transform((value, originalValue, context) => {

// check to see if the previous transform already parsed the date

if (context.isType(value)) return value;

// the default coercion failed so let's try it with Moment.js instead

value = Moment(originalValue, formats);

// if it's valid return the date object, otherwise return an `InvalidDate`

return value.isValid() ? value.toDate() : new Date('');

});

};

mixed

Creates a schema that matches all types, or just the ones you configure. Inherits from Schema.

Mixed types extends {} by default instead of any or unknown. This is because in TypeScript {} means

anything that isn't null or undefined which yup treats distinctly.

import { mixed, InferType } from 'yup';

let schema = mixed().nullable();

schema.validateSync('string'); // 'string';

schema.validateSync(1); // 1;

schema.validateSync(new Date()); // Date;

InferType; // {} | undefined

InferType; // {} | null

Custom types can be implemented by passing a type check function. This will also

narrow the TypeScript type for the schema.

import { mixed, InferType } from 'yup';

let objectIdSchema = yup

.mixed((input): input is ObjectId => input instanceof ObjectId)

.transform((value: any, input, ctx) => {

if (ctx.isType(value)) return value;

return new ObjectId(value);

});

await objectIdSchema.validate(ObjectId('507f1f77bcf86cd799439011')); // ObjectId("507f1f77bcf86cd799439011")

await objectIdSchema.validate('507f1f77bcf86cd799439011'); // ObjectId("507f1f77bcf86cd799439011")

InferType; // ObjectId

string

Define a string schema. Inherits from Schema.

let schema = yup.string();

await schema.isValid('hello'); // => true

By default, the cast logic of string is to call toString on the value if it exists.

empty values are not coerced (use ensure() to coerce empty values to empty strings).

Failed casts return the input value.

string.required(message?: string | function): Schema

The same as the mixed() schema required, except that empty strings are also considered 'missing' values.

string.length(limit: number | Ref, message?: string | function): Schema

Set a required length for the string value. The ${length} interpolation can be used in the message argument

string.min(limit: number | Ref, message?: string | function): Schema

Set a minimum length limit for the string value. The ${min} interpolation can be used in the message argument

string.max(limit: number | Ref, message?: string | function): Schema

Set a maximum length limit for the string value. The ${max} interpolation can be used in the message argument

string.matches(regex: Regex, message?: string | function): Schema

Provide an arbitrary regex to match the value against.

let schema = string().matches(/(hi|bye)/);

await schema.isValid('hi'); // => true

await schema.isValid('nope'); // => false

string.matches(regex: Regex, options: { message: string, excludeEmptyString: bool }): Schema

An alternate signature for string.matches with an options object. excludeEmptyString, when true,

short circuits the regex test when the value is an empty string, making it a easier to avoid

matching nothing without complicating the regex.

let schema = string().matches(/(hi|bye)/, { excludeEmptyString: true });

await schema.isValid(''); // => true

string.email(message?: string | function): Schema

Validates the value as an email address using the same regex as defined by the HTML spec.

WATCH OUT: Validating email addresses is nearly impossible with just code. Different

clients and servers accept different things and many diverge from the various specs defining

"valid" emails. The ONLY real way to validate an email address is to send a verification email

to it and check that the user got it. With that in mind, yup picks a relatively simple regex

that does not cover all cases, but aligns with browser input validation behavior since HTML

forms are a common use case for yup.

If you have more specific needs please override the email method with your own logic or regex:

yup.addMethod(yup.string, 'email', function validateEmail(message) {

return this.matches(myEmailRegex, {

message,

name: 'email',

excludeEmptyString: true,

});

});

string.url(message?: string | function): Schema

Validates the value as a valid URL via a regex.

string.uuid(message?: string | function): Schema

Validates the value as a valid UUID via a regex.

string.datetime(options?: {message?: string | function, allowOffset?: boolean, precision?: number})

Validates the value as an ISO datetime via a regex. Defaults to UTC validation; timezone offsets are not permitted (see options.allowOffset).

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

options.allowOffset: Allow a time zone offset. False requires UTC 'Z' timezone. (default: false)

options.precision: Require a certain sub-second precision on the date. (default: null -- any (or no) sub-second precision)

string.datetime(message?: string | function)

An alternate signature for string.datetime that can be used when you don't need to pass options other than message.

string.ensure(): Schema

Transforms undefined and null values to an empty string along with

setting the default to an empty string.

string.trim(message?: string | function): Schema

Transforms string values by removing leading and trailing whitespace. If

strict() is set it will only validate that the value is trimmed.

string.lowercase(message?: string | function): Schema

Transforms the string value to lowercase. If strict() is set it

will only validate that the value is lowercase.

string.uppercase(message?: string | function): Schema

Transforms the string value to uppercase. If strict() is set it

will only validate that the value is uppercase.

number

Define a number schema. Inherits from Schema.

let schema = yup.number();

await schema.isValid(10); // => true

The default cast logic of number is: parseFloat.

Failed casts return NaN.

number.min(limit: number | Ref, message?: string | function): Schema

Set the minimum value allowed. The ${min} interpolation can be used in the

message argument.

number.max(limit: number | Ref, message?: string | function): Schema

Set the maximum value allowed. The ${max} interpolation can be used in the

message argument.

number.lessThan(max: number | Ref, message?: string | function): Schema

Value must be less than max. The ${less} interpolation can be used in the

message argument.

number.moreThan(min: number | Ref, message?: string | function): Schema

Value must be strictly greater than min. The ${more} interpolation can be used in the

message argument.

number.positive(message?: string | function): Schema

Value must be a positive number.

number.negative(message?: string | function): Schema

Value must be a negative number.

number.integer(message?: string | function): Schema

Validates that a number is an integer.

number.truncate(): Schema

Transformation that coerces the value to an integer by stripping off the digits

to the right of the decimal point.

number.round(type: 'floor' | 'ceil' | 'trunc' | 'round' = 'round'): Schema

Adjusts the value via the specified method of Math (defaults to 'round').

boolean

Define a boolean schema. Inherits from Schema.

let schema = yup.boolean();

await schema.isValid(true); // => true

date

Define a Date schema. By default ISO date strings will parse correctly,

for more robust parsing options see the extending schema types at the end of the readme.

Inherits from Schema.

let schema = yup.date();

await schema.isValid(new Date()); // => true

The default cast logic of date is pass the value to the Date constructor, failing that, it will attempt

to parse the date as an ISO date string.

If you would like ISO strings to not be cast to a Date object, use .datetime() instead.

Failed casts return an invalid Date.

date.min(limit: Date | string | Ref, message?: string | function): Schema

Set the minimum date allowed. When a string is provided it will attempt to cast to a date first

and use the result as the limit.

date.max(limit: Date | string | Ref, message?: string | function): Schema

Set the maximum date allowed, When a string is provided it will attempt to cast to a date first

and use the result as the limit.

array

Define an array schema. Arrays can be typed or not, When specifying the element type, cast and isValid

will apply to the elements as well. Options passed into isValid are also passed to child schemas.

Inherits from Schema.

let schema = yup.array().of(yup.number().min(2));

await schema.isValid([2, 3]); // => true

await schema.isValid([1, -24]); // => false

schema.cast(['2', '3']); // => [2, 3]

You can also pass a subtype schema to the array constructor as a convenience.

array().of(yup.number());

// or

array(yup.number());

Arrays have no default casting behavior.

array.of(type: Schema): this

Specify the schema of array elements. of() is optional and when omitted the array schema will

not validate its contents.

array.json(): this

Attempt to parse input string values as JSON using JSON.parse.

array.length(length: number | Ref, message?: string | function): this

Set a specific length requirement for the array. The ${length} interpolation can be used in the message argument.

array.min(limit: number | Ref, message?: string | function): this

Set a minimum length limit for the array. The ${min} interpolation can be used in the message argument.

array.max(limit: number | Ref, message?: string | function): this

Set a maximum length limit for the array. The ${max} interpolation can be used in the message argument.

array.ensure(): this

Ensures that the value is an array, by setting the default to [] and transforming null and undefined

values to an empty array as well. Any non-empty, non-array value will be wrapped in an array.

array().ensure().cast(null); // => []

array().ensure().cast(1); // => [1]

array().ensure().cast([1]); // => [1]

array.compact(rejector: (value) => boolean): Schema

Removes falsey values from the array. Providing a rejecter function lets you specify the rejection criteria yourself.

array().compact().cast(['', 1, 0, 4, false, null]); // => [1, 4]

array()

.compact(function (v) {

return v == null;

})

.cast(['', 1, 0, 4, false, null]); // => ['', 1, 0, 4, false]

tuple

Tuples, are fixed length arrays where each item has a distinct type.

Inherits from Schema.

import { tuple, string, number, InferType } from 'yup';

let schema = tuple([

string().label('name'),

number().label('age').positive().integer(),

]);

await schema.validate(['James', 3]); // ['James', 3]

await schema.validate(['James', -24]); // => ValidationError: age must be a positive number

InferType // [string, number] | undefined

tuples have no default casting behavior.

object

Define an object schema. Options passed into isValid are also passed to child schemas.

Inherits from Schema.

yup.object({

name: string().required(),

age: number().required().positive().integer(),

email: string().email(),

website: string().url(),

});

object schema do not have any default transforms applied.

Object schema defaults

Object schema come with a default value already set, which "builds" out the object shape, a

sets any defaults for fields:

const schema = object({

name: string().default(''),

});

schema.default(); // -> { name: '' }

This may be a bit surprising, but is usually helpful since it allows large, nested

schema to create default values that fill out the whole shape and not just the root object. There is

one gotcha! though. For nested object schema that are optional but include non optional fields

may fail in unexpected ways:

const schema = object({

id: string().required(),

names: object({

first: string().required(),

}),

});

schema.isValid({ id: 1 }); // false! names.first is required

This is because yup casts the input object before running validation

which will produce:

{ id: '1', names: { first: undefined }}

During the validation phase names exists, and is validated, finding names.first missing.

If you wish to avoid this behavior do one of the following:

Set the nested default to undefined: names.default(undefined)

mark it nullable and default to null: names.nullable().default(null)

object.shape(fields: object, noSortEdges?: Array<[string, string]>): Schema

Define the keys of the object and the schemas for said keys.

Note that you can chain shape method, which acts like Object.assign.

object({

a: string(),

b: number(),

}).shape({

b: string(),

c: number(),

});

would be exactly the same as:

object({

a: string(),

b: string(),

c: number(),

});

object.json(): this

Attempt to parse input string values as JSON using JSON.parse.

object.concat(schemaB: ObjectSchema): ObjectSchema

Creates a object schema, by applying all settings and fields from schemaB to the base, producing a new schema.

The object shape is shallowly merged with common fields from schemaB taking precedence over the base

fields.

object.pick(keys: string[]): Schema

Create a new schema from a subset of the original's fields.

const person = object({

age: number().default(30).required(),

name: string().default('pat').required(),

color: string().default('red').required(),

});

const nameAndAge = person.pick(['name', 'age']);

nameAndAge.getDefault(); // => { age: 30, name: 'pat'}

object.omit(keys: string[]): Schema

Create a new schema with fields omitted.

const person = object({

age: number().default(30).required(),

name: string().default('pat').required(),

color: string().default('red').required(),

});

const nameAndAge = person.omit(['color']);

nameAndAge.getDefault(); // => { age: 30, name: 'pat'}

object.from(fromKey: string, toKey: string, alias: boolean = false): this

Transforms the specified key to a new key. If alias is true then the old key will be left.

let schema = object({

myProp: mixed(),

Other: mixed(),

})

.from('prop', 'myProp')

.from('other', 'Other', true);

schema.cast({ prop: 5, other: 6 }); // => { myProp: 5, other: 6, Other: 6 }

object.noUnknown(onlyKnownKeys: boolean = true, message?: string | function): Schema

Validate that the object value only contains keys specified in shape, pass false as the first

argument to disable the check. Restricting keys to known, also enables stripUnknown option, when not in strict mode.

object.camelCase(): Schema

Transforms all object keys to camelCase

object.constantCase(): Schema

Transforms all object keys to CONSTANT_CASE.

ReadmeKeywordsnonePackage SidebarInstallnpm i yupRepositoryGitgithub.com/jquense/yupHomepagegithub.com/jquense/yupDownloadsWeekly Downloads5,961,665Version1.4.0LicenseMITUnpacked Size256 kBTotal Files6Last publisha day agoCollaboratorsTry on RunKitReport malware FooterSupportHelpAdvisoriesStatusContact npmCompanyAboutBlogPressTerms & PoliciesPoliciesTerms of UseCode of ConductPrivacy

yep(美国俚语、网络流行词)_百度百科

美国俚语、网络流行词)_百度百科 网页新闻贴吧知道网盘图片视频地图文库资讯采购百科百度首页登录注册进入词条全站搜索帮助首页秒懂百科特色百科知识专题加入百科百科团队权威合作下载百科APP个人中心yep是一个多义词,请在下列义项上选择浏览(共3个义项)展开添加义项yep播报讨论上传视频美国俚语、网络流行词收藏查看我的收藏0有用+10yep,美国俚语,就是“是”的意思,和yes的意思差不多。yep 是俚语,意思与yup一样。使用yep、yup更加俏皮一些,适用于网络、通常会话中使用。外文名yep别    名yes性    质网络流行词全    称your educational plans含    义表示肯定或赞成对方的口吻,也可以表示欣赏他人说法做法的口吻目录1词语来源2发展经过3引用示例词语来源播报编辑yep,是全称“your educational plans”(个人教育计划)的缩略语。属于美语的俚语。与“yup”一样,属非正式场合及书面用语。表示肯定或赞成对方的口吻,也可以表示欣赏他人说法做法的口吻。 [1]发展经过播报编辑虽然yep、yup等词与yes的字面解释相同,但是使用yep、yup更加俏皮一些,适用于网络、通常会话中使用。而且多用于同辈人,朋友之间。请勿用于长辈,老师,因为yep、yup多少有点随意,不太尊重。如果是在正式场合,请使用yes。yes属于正式场合及书面用语。 [1]引用示例播报编辑实际应用中,yep,yup跟yes在口语中有很大区别。 yep、yup均来源于印第安语与英语的演化。事实上,在美国中部,西部地区、加拿大、澳大利亚、新西兰口语中yep、yup常用于回答人家的感谢或表示肯定、赞成等;yep也是西方人回应Thank you的方式之一,而且流行程度远远超过You are welcome. 常见于餐厅,网络等非正式场合。 [1]新手上路成长任务编辑入门编辑规则本人编辑我有疑问内容质疑在线客服官方贴吧意见反馈投诉建议举报不良信息未通过词条申诉投诉侵权信息封禁查询与解封©2024 Baidu 使用百度前必读 | 百科协议 | 隐私政策 | 百度百科合作平台 | 京ICP证030173号 京公网安备110000020000

YUP中文(繁體)翻譯:劍橋詞典

YUP中文(繁體)翻譯:劍橋詞典

詞典

翻譯

文法

同義詞詞典

+Plus

劍橋詞典+Plus

Shop

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

登錄

/

註冊

正體中文 (繁體)

查找

查找

英語-中文(繁體)

yup 在英語-中文(繁體)詞典中的翻譯

yupadverb

  informal uk

Your browser doesn't support HTML5 audio

/jʌp/ us

Your browser doesn't support HTML5 audio

/jʌp/

Add to word list

Add to word list

(spelled the way it is spoken) yes

(口語)是,對

"Can you see it?" "Yup, there it is."

「你看得見嗎?」「是,在那裡呢。」

(yup在劍橋英語-中文(繁體)詞典的翻譯 © Cambridge University Press)

yup的例句

yup

Yup, it's wrong, but it's understandable!

來自 Wikipedia

該例句來自維基百科,在CC BY-SA許可下可重複使用。

Yup, he's coming to check me out.

來自 Wikipedia

該例句來自維基百科,在CC BY-SA許可下可重複使用。

示例中的觀點不代表劍橋詞典編輯、劍橋大學出版社和其許可證頒發者的觀點。

C1

yup的翻譯

中文(簡體)

(口语)是,对…

查看更多內容

西班牙語

sí…

查看更多內容

需要一個翻譯器嗎?

獲得快速、免費的翻譯!

翻譯器工具

yup的發音是什麼?

在英語詞典中查看 yup 的釋義

瀏覽

Yuletide

yum

yummy

yummy mummy

yup

yuppie

yuppify

yurt

yute

「每日一詞」

veggie burger

UK

Your browser doesn't support HTML5 audio

/ˈvedʒ.i ˌbɜː.ɡər/

US

Your browser doesn't support HTML5 audio

/ˈvedʒ.i ˌbɝː.ɡɚ/

a type of food similar to a hamburger but made without meat, by pressing together small pieces of vegetables, seeds, etc. into a flat, round shape

關於這個

部落格

Forget doing it or forget to do it? Avoiding common mistakes with verb patterns (2)

March 06, 2024

查看更多

新詞

stochastic parrot

March 04, 2024

查看更多

已添加至 list

回到頁面頂端

內容

英語-中文(繁體)例句翻譯

©劍橋大學出版社與評估2024

學習

學習

學習

新詞

幫助

紙本出版

Word of the Year 2021

Word of the Year 2022

Word of the Year 2023

開發

開發

開發

詞典API

連按兩下查看

搜尋Widgets

執照資料

關於

關於

關於

無障礙閱讀

劍橋英語教學

劍橋大學出版社與評估

授權管理

Cookies與隱私保護

語料庫

使用條款

京ICP备14002226号-2

©劍橋大學出版社與評估2024

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

詞典

定義

清晰解釋自然的書面和口頭英語

英語

學習詞典

基礎英式英語

基礎美式英語

翻譯

點選箭頭改變翻譯方向。

雙語詞典

英語-中文(簡體)

Chinese (Simplified)–English

英語-中文(繁體)

Chinese (Traditional)–English

英語-荷蘭文

荷蘭語-英語

英語-法語

法語-英語

英語-德語

德語-英語

英語-印尼語

印尼語-英語

英語-義大利語

義大利語-英語

英語-日語

日語-英語

英語-挪威語

挪威語-英語

英語-波蘭語

波蘭語-英語

英語-葡萄牙語

葡萄牙語-英語

英語-西班牙語

西班牙語-英語

English–Swedish

Swedish–English

半雙語詞典

英語-阿拉伯語

英語-孟加拉文

英語-加泰羅尼亞語

英語-捷克語

英語-丹麥語

English–Gujarati

英語-印地語

英語-韓語

英語-馬來語

英語-馬拉地語

英語-俄語

English–Tamil

English–Telugu

英語-泰語

英語-土耳其語

英語-烏克蘭文

English–Urdu

英語-越南語

翻譯

文法

同義詞詞典

Pronunciation

劍橋詞典+Plus

Shop

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

登錄 /

註冊

正體中文 (繁體)  

Change

English (UK)

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

中文 (简体)

正體中文 (繁體)

Polski

한국어

Türkçe

日本語

Tiếng Việt

हिंदी

தமிழ்

తెలుగు

關注我們!

選擇一本詞典

最近的詞和建議

定義

清晰解釋自然的書面和口頭英語

英語

學習詞典

基礎英式英語

基礎美式英語

文法與同義詞詞典

對自然書面和口頭英語用法的解釋

英語文法

同義詞詞典

Pronunciation

British and American pronunciations with audio

English Pronunciation

翻譯

點選箭頭改變翻譯方向。

雙語詞典

英語-中文(簡體)

Chinese (Simplified)–English

英語-中文(繁體)

Chinese (Traditional)–English

英語-荷蘭文

荷蘭語-英語

英語-法語

法語-英語

英語-德語

德語-英語

英語-印尼語

印尼語-英語

英語-義大利語

義大利語-英語

英語-日語

日語-英語

英語-挪威語

挪威語-英語

英語-波蘭語

波蘭語-英語

英語-葡萄牙語

葡萄牙語-英語

英語-西班牙語

西班牙語-英語

English–Swedish

Swedish–English

半雙語詞典

英語-阿拉伯語

英語-孟加拉文

英語-加泰羅尼亞語

英語-捷克語

英語-丹麥語

English–Gujarati

英語-印地語

英語-韓語

英語-馬來語

英語-馬拉地語

英語-俄語

English–Tamil

English–Telugu

英語-泰語

英語-土耳其語

英語-烏克蘭文

English–Urdu

英語-越南語

詞典+Plus

詞彙表

選擇語言

正體中文 (繁體)  

English (UK)

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

中文 (简体)

Polski

한국어

Türkçe

日本語

Tiếng Việt

हिंदी

தமிழ்

తెలుగు

內容

英語-中文(繁體) 

 Adverb

例句

Translations

文法

所有翻譯

我的詞彙表

把yup添加到下面的一個詞彙表中,或者創建一個新詞彙表。

更多詞彙表

前往詞彙表

對該例句有想法嗎?

例句中的單詞與輸入詞條不匹配。

該例句含有令人反感的內容。

取消

提交

例句中的單詞與輸入詞條不匹配。

該例句含有令人反感的內容。

取消

提交

yup是什么意思_yup的翻译_音标_读音_用法_例句_爱词霸在线词典

什么意思_yup的翻译_音标_读音_用法_例句_爱词霸在线词典首页翻译背单词写作校对词霸下载用户反馈专栏平台登录yup是什么意思_yup用英语怎么说_yup的翻译_yup翻译成_yup的中文意思_yup怎么读,yup的读音,yup的用法,yup的例句翻译人工翻译试试人工翻译翻译全文yup英 [jʌp]美 [jʌp]释义int.<美俚>是,是的(肯定答复)大小写变形:YUP点击 人工翻译,了解更多 人工释义实用场景例句全部Yup. I graduated in 1937.是的, 我是一九三七年毕业的.辞典例句Sergio: Yup, it was me and without any help.塞吉奥: 是, 是我,而且没请人帮忙.互联网SS : yup, i'll only understand if you tell me out loud.三顺: 只有你大声的告诉我了, 我才明白啊!互联网Yup. And if I'm not back in 24 hours, call a cat.是的. 如果我24小时都没回来, 召集猫.互联网Yup , they are perfect. When should I add the garlic?很好. 什么时候该加大蒜 呢 ?互联网B : Yup ! I also like clam soup and sea cucumbers.对 呀! 我还喜欢蛤仔汤和海参.互联网B: Yup. We have one coming up the first of June.乙: 是的, 我们有一套房子6月1日就能空出来.互联网Yup , I always write some small , messy essays sometimes.呵呵, 有时还会幼稚的写些又短又散乱的文章.互联网Yup, conflict and violence – everyday life for bottlenose dolphin.是的, 冲突和暴力–宽吻海豚的日常生活.互联网Yup. And if I'm not back in 24 hours, call a cat.是的. 如果我24小时都没回来, 买只猫. (此处借鉴配音版翻译)互联网Yup, I think I could wet my tonsils after that long ride.是呀,开车开了这么久, 我想能够喝上一杯了.互联网Now, just make your way down the stage this way , yup.现在, 从这边下到舞台上, 是的.互联网Yup. And that's what he did.是的. 而他正是这么做的.互联网Yup and here is the three amigos.是这里是三个好友们.互联网Yup, it's LeBron's hubris we hear.是的, 我们听到了勒布朗的豪言壮语.互联网收起实用场景例句释义实用场

yup_百度百科

百度百科 网页新闻贴吧知道网盘图片视频地图文库资讯采购百科百度首页登录注册进入词条全站搜索帮助首页秒懂百科特色百科知识专题加入百科百科团队权威合作下载百科APP个人中心收藏查看我的收藏0有用+10yup播报讨论上传视频英语单词yup,英语单词,主要用作感叹词、副词、名词,作感叹词时译为“是的(等于 yep)”,作副词时译为“是的(等于 yes)”,作名词时译为“(非正式)雅皮士(城市中收入高、生活优裕的年轻专业人员)(等于 yuppie)”。 [1]外文名yup词    性感叹词、副词、名词英式发音[jʌp]美式发音[jʌp]目录1短语搭配2双语例句短语搭配播报编辑See Yup 型人物如四邑Yup yup 没错Kang Yup 发明人whispers yup 烨小声YUP PRO 合卡套件版本Sam Yup 三邑总会馆Haha Yup 哈哈啊Paik In Yup 白寅桦Yup Extra Clbumico 典范亚麻 [1]双语例句播报编辑In a new interview, Hillary Clinton said she originally turned down the job as secretary of state. Yup.在一个新的采访中,希拉里·克林顿说她本来是拒绝了国务卿的工作的。Included among these cells are hairs (yup, leaves have hairs), any sort of bump or ornamentation, and most important, stomata.在这些细胞中包裹着绒毛(是的,叶子有绒毛),某种肿块或装饰,还有最重要的——气孔。Yup, he was a handful, and I reveled in his passionate pursuits.是的,他个性鲜明,我沉醉于他热情的追求之中。 [1]新手上路成长任务编辑入门编辑规则本人编辑我有疑问内容质疑在线客服官方贴吧意见反馈投诉建议举报不良信息未通过词条申诉投诉侵权信息封禁查询与解封©2024 Baidu 使用百度前必读 | 百科协议 | 隐私政策 | 百度百科合作平台 | 京ICP证030173号 京公网安备110000020000

yup 动态验证 - 初探 - 掘金

yup 动态验证 - 初探 - 掘金

首页 首页

沸点

课程

直播

活动

竞赛

商城

APP

插件 搜索历史

清空

创作者中心

写文章 发沸点 写笔记 写代码 草稿箱 创作灵感

查看更多

会员

登录

注册

yup 动态验证 - 初探

清香的orange

2022-12-15

1,361

Yup

官方解释:

Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformations.

大致译为:

Yup 是一个用于值解析和验证的 JavaScript 架构构建器。 定义模式、转换值以匹配、验证现有值的形状,或两者兼而有之。 Yup 模式具有极强的表现力,允许对复杂的、相互依赖的验证或值转换进行建模。

Schema

schema 是对数据的一种描述。例:yup.string() 描述数据是字符串类型。我们可以 required、min,max 等修饰方法对其进行修饰,也可以使用 test 方法来订制更复杂的描述。

除了 string,yup 还内置了 number、boolean、data、array、object 模式,它们都继承于 mixed 模式。通过 mixed 我们可以对 schema 进行订制 。

依据使用的方式将 schema 大致划分为以下两大类 schema types 和 schema types。

type schema

type schema 主要包含有 mixed、string、number、boolean、date、array、object 等。

yup.mixed()

mixed.cast()

mixed.cast(value: any, options = {}): any

尝试将传入的值强制转换为与模式匹配的值,转换失败的话可能返回 null、NaN 或其他字符信息。

示例:

// 数字类型 1 将会转化为字符串 '1'

yup.string().min(2).required().cast(1)

mixed.when()

mixed.when(keys: string | Array, builder: object | (value, schema)=> Schema): Schema

通过同级或同级子字段作为判定条件来对其他字段匹配 schema。

示例:

// 方式一:is~then/otherwise 形式

let schema = object({

isBig: boolean(),

count: number()

.when('isBig', {

// is: (val) => val == true,

is: true,

then: yup.number().min(5), // isBig 为 true 时 count 使用该 schema

otherwise: yup.number().min(0), // isBig 不为 true 时 count 使用该 schema

})

// $other 可以替换 options 参数内 context 对象中的值

.when('$other', (other, schema) => (other === 4 ? schema.max(6) : schema)), // schema.max(6) 生效

});

// 方式二:回调函数形式

let schema = yup.object({

isBig: yup.boolean(),

count: yup.number().when('isBig', (isBig, schema) => {

return isBig ? schema.min(5) : schema.min(0);

}),

});

await schema.validate({ isBig: true, count: 4 }, { context: { other: 4 } });

mixed.test()

mixed.test(name: string, message: string | function, testFun: function): Schema

向验证链添加测试函数。在投射任何对象后运行测试定制特定逻辑的验证提示信息。

testFun function

普通函数 function (val) {}

箭头函数 (val, context) => {}

说明:测试函数为普通函数上下文对象为 函数内 this;为箭头函数上下文对象为函数第二个参数 context。

context type

type ContextType = {

path: string // 当前验证的路径字符串

schema: object // 测试运行所针对的解析模式对象

options: object // 调用 validate() 或 isValid() 的选项对象

parent: object // 嵌套模式下父对象的值

originalValue: any // 验证的源数据信息

createError: { path: string; message: string; params: object } // 创建并返回验证错误

}

示例:

// 提示信息中的 path 变量见上面 ContextType 对象属性说明

// 同步校验

let jerrySchema = yup.string().require('名称不能为空').test(

'isJerry',

'${path}名称不正确,不是 Jerry', // 默认错误提示信息【回调函数返回 false 时使用】

(val, context) => {

if (val !== 'Jerry') {

// 提示 createError 创建的错误信息【将覆盖默认错误信息提示】

retrun context.createError({

message: '名称不正确,不是 Jerry',

})

}

return true;

}

)

// 异步校验

let asyncJerrySchema = yup.string().require('名称不能为空').test(

'isJerry',

'${path}名称不正确,不是 Jerry', // 默认错误提示信息

async (val, context) => {

const res = await fetch('/isJerry/' + val);

// true 存在校验通过,false 时不存在显示默认错误提示信息

return res.data;

}

)

await jerrySchema.isValid('Jerry'); // => true

await asyncJerrySchema.isValid('Tom'); // => false

yup.array()

array.of()

array.of(type: Schema): Schema

指定数组元素的架构。 of() 是可选的,当省略时,数组模式将不会验证其内容。

示例:

let schema = yup.array().of(

// yup.object({...}) 与 yup.object().shape({...}) 在这等同,详情见下文 yub.object().shape()

yup.object().shape({

name: yup

.string().trim()

.max(50, '不能超过 50 字符')

.required('姓名不能为空')

.test(

'name',

'名称不正确,不是 Jerry',

(val) => val === 'Jerry'

),

age: yup.number().min(0, '年龄不能小于 0').required('年龄不能为空')

})

)

await schema.validate([{ name: 'Arvinjun', age: 18 }]);

yup.object()

object.shape()

object.shape(fields: object, noSortEdges?: Array<[string, string]>): Schema

定义对象的键和所述键的模式。 请注意,您可以链接形状方法,其作用类似于对象扩展。

示例:

object({

a: string(),

b: number(),

}).shape({

b: string(),

c: number(),

});

// 等同于

object({

a: string(),

b: string(),

c: number(),

});

method schema

method schema 主要包含有 reach、addMethod、ref、lazy、ValidtionError 等。

lazy()

yup.lazy((value: any) => Schema): Lazy

创建在验证/转换时评估的架构。对于为多态字段和数组创建递归模式(如树)很有用。

注意 ⚠️:在定义父子递归对象模式时,您需要将子对象的 default() 重置为 undefined, 否则当您强制转换对象时,对象将会无限嵌套!

示例:

let node = object({

id: number(),

child: yup.lazy(() => node.default(undefined)),

});

let renderable = yup.lazy((val) => {

switch (typeof val) {

case 'number':

return number();

case 'string':

return string();

default:

return mixed();

}

});

let renderables = array().of(renderable);

References

yup official document

清香的orange

43

文章

121k

阅读

36

粉丝 目录 收起

Yup

Schema

type schema

yup.mixed()

mixed.cast()

mixed.when()

mixed.test()

yup.array()

array.of()

yup.object()

object.shape()

method schema

lazy()

References

友情链接:

别时容易见时难全诗

莎士比亚故事集免费阅读

人人都是项目经理读后感

十批判书 小说

18岁男子与兄弟女友同床共眠

洛婉恩爆料肖战是财富密码