我试图使用Formik + Yup编写一个用于模式验证的react本机应用程序,并且在提取max验证中通过的常量时遇到了一些困难。
让我们想象一下以下模式:
const message = string()
.max(30)
.default(1)
在中,假设是自定义的TextInput
,我希望获得常量30
,以便将其传递给maxLength
支柱:
<TextInput maxLength={max} {...otherProps} />
(当然,模式是简化的)
有人知道这是否可行吗?如何深入研究yup模式来访问该常量并将其传递给我的TextInput
发布于 2020-05-10 06:26:40
调用schema.describe()。这将返回模式的描述,包括“测试”数组。测试数组中的项之一将具有名称"max",以及包含"max“值的"params”对象。
const description = schema.describe();
const maxTest = description.tests.find(t => t.name === 'max');
const maxValue = maxTest && maxTest.params ? maxTest.params.max : undefined;
您应该能够以同样的方式访问大多数验证,但是目前还没有一种方法来了解像‘小写’和‘带状’这样的转换是否被应用。
当然,您必须公开每个字段的架构才能完成上述操作。或者,您可以对父对象模式调用describe()并询问“field”属性,然后执行类似于上面的操作。
发布于 2019-09-04 13:20:02
您可以将一个function
传递给validationSchema
支柱,所以基本上您的yup
模式是,
const validationSchema = value => Yup.object().shape({
name : Yup.string().max(values.max).default(1)
});
在<Formik/>
组件级呈现方法中,
const { max } = this.state;
<Formik
validationSchema={()=> validationSchema({max})
...>
<TextInput maxLength={max} {...otherProps} />
</Formik>
https://stackoverflow.com/questions/57788278
复制相似问题