@felte/验证器-yup
在 Felte 中帮助您处理 Yup 验证的软件包 .
安装
npm install --save @felte/validator-yup yup
# Or, if you use yarn
yarn add @felte/validator-yup yup
使用量
打电话 validator 含有您 YUP 方案的内容 schema 属性。 调用的结果可以作为延伸器传递给费尔特:
import { validator } from '@felte/validator-yup';
import * as yup from 'yup';
const schema = yup.object({
email: yup.string().email().required(),
password: yup.string().required(),
});
const { form } = createForm({
// ...
extend: validator({ schema }), // or `extend: [validator({ schema })],`
// ...
});
使用 validateSchema 函数直接在 validate 选项 createForm. (不需要延长Felte).
import { validateSchema } from '@felte/validator-yup';
import * as yup from 'yup';
const schema = yup.object({
email: yup.string().email().required(),
password: yup.string().required(),
});
const { form } = createForm({
// ...
validate: validateSchema(schema),
// ...
});
铸造价值
与 yup,默认情况下,此验证符会 没有 铸造价值。 如果你想有这种行为,你可以设置 castValues 属性改为 true 在验证符的配置上 :
const { form } = createForm({
//...
extend: validator({ schema, castValues: true }),
//...
});
页:1数字 : yup 如果你的计谋失败了,就抛出, 我们没有抓住这个错误 所以,确保你的计划 处理得当 防止你的应用程序崩溃。 比如,让我们假设我们有一个 text 输入应投入整数. yup是因为 number 如果设置了字符串,规则会出错,为了防止您的应用程序崩溃,需要自定义规则:
const schema = yup.object({
shouldBeNumber: yup
.mixed()
.test('number', 'Must be a number', value => !isNaN(value))
.transform(value => parseInt(value, 10)),
});
警告
您可以选择让此软件包指定您验证的结果 warnings 通过设置存储 level 校验函数的属性 warning这是 error 默认:
import { validator } from '@felte/validator-yup';
import * as yup from 'yup';
const validateSchema = yup.object({
email: yup.string().email().required(),
password: yup.string().required(),
});
// We only warn if the user has already started typing a value
const warnSchema = yup.object({
password: yup
.string()
.test('is-secure', 'password is not secure', (value) =>
value ? value.length > 8 : true
),
});
const { form } = createForm({
// ...
extend: [
validator({ schema }),
validator({ schema: warnSchema, level: 'warning' }),
],
// ...
});
字体
是的 让你可以推断出你的计划 yup.InferType。这个可以使用,因此不需要为表单数据创建类型:
import * as yup from 'yup';
const schema = yup.object({
email: yup.string().email().required(),
password: yup.string().required(),
});
const { form } = createForm<yup.InferType<typeof schema>>(/* ... */);