安装和配置

安装

这里使用 yarn 安装

1
$ yarn add yup
image-20230922233349102

配置

  • 按需引入

    1
    import { object, string } from "yup";
  • 全部引入

    1
    import * as yup from "yup";

How to 使用(以登陆验证为例)

创建验证架构

定义对象架构,并使用架构调用附加到该方法的方法

1
const loginSchema = yup.object().shape({})

或者在方法中传递架构

1
const loginSchema = yup.object({})

由于需要对字符串验证,所以需要使用方法 string() 定义字符串架构

对于邮件和密码的 check:

1
2
3
4
const loginSchema = yup.object().shape({
email: yup.string().required().email(),
password: yup.string().required()
})

我们还可以添加其他更多的验证方法,可以在 yup 文档中查看

添加 check

定义验证方法

首先我们要定义验证方法,验证方法会根据验证架构验证单个字段

我们可以在回调中获取验证错误信息

1
2
3
4
5
6
7
8
9
10
11
const inputCheck = (field: string) => {
loginSchema
.validateAt(field, state.value)
.then(() => {
// 在验证通过时,需要清空错误信息
state.errorMsg[field] = ''
})
.catch(err => {
state.errorMsg[field] = err.errorMsg
})
}

如果用户点击 button 提交表单时触发该方法, 默认情况下如果在发现错误后会立刻进入 catch 中,不会验证其他任何的字段,要避免这个需要传递 abortEarly: false

1
2
3
4
5
6
7
8
9
10
11
12
const inputCheck = (field: string, {abortEarly: false}) => {
loginSchema
.validateAt(field, state.value)
.then(() => {
state.errorMsg[field] = ''

// login()
})
.catch(err => {
state.errorMsg[field] = err.errorMsg
})
}

表单中添加 check 方法

在输入框矢焦时触发

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<input
id="email"
name="email"
type="email"
v-model="state.value.email"
@blur="inputCheck('email')"
/>
<input
id="password"
name="password"
type="password"
v-model="state.value.password"
@blur="inputCheck('password')"
/>

使用 test() 方法自定义 check 规则

虽然可以使用 when() 或 ref 进行复杂的验证,但是由于灵活性不强,所以可以使用 test() 方法进行复杂验证

这里以 numA === numB + numC 为例

首先要创建验证架构

numA、numB、numC 需要是数字类型 number() ,并且不为空 required()

之后在 test() 自定义 check 规则,并返回 check 结果( truefalse

1
2
3
4
5
6
7
8
9
const numSchema = yup.object().shape({
numA: yup.number().required().test('numASchema', 'defalutMsg', function (numA) {
const numB = this.parent.numB;
const numC = this.parent.numC;
return numA === numB * numC;
}),
numB: yup.number().required(),
numC: yup.number().required(),
})

然后定义验证方法

1
2
3
4
5
6
7
8
9
10
const numCheck = (field: string) => {
numSchema
.validateAt(field, state.value)
.then(() => {
state.errorMsg[field] = '';
})
.catch(() => {
state.errorMsg[field] = field + ' check error';
})
}

最后在表单或 button 绑定验证方法即可🙃