She*_*shi 7 forms reactjs yup formik react-hooks
我正在尝试使用 Formik 和 Yup 实现登录功能。这是我当前的架构
let loginSchema = yup.object().shape({loginId:
yup
.string()
.email("That doesn't look like a valid email")
.required("This field is required."),password: yup.string().required("This field is required."),});
Run Code Online (Sandbox Code Playgroud)
但我的登录ID可以是电话号码或电子邮件。那么,如何根据表单中输入的字段类型添加验证。如果是电子邮件,则触发电子邮件验证,或者如果是电话号码,我想根据正则表达式对其进行验证。
如果您想动态验证字段,请when使用validationSchema. 文档中的示例。
let schema = object({
isBig: boolean(),
count: number()
.when('isBig', {
is: true, // alternatively: (val) => val == true
then: yup.number().min(5),
otherwise: yup.number().min(0),
})
.when('$other', (other, schema) => (other === 4 ? schema.max(6) : schema)),
});
Run Code Online (Sandbox Code Playgroud)
因此,在您的情况下,您必须编写is声明来确定它是否是电话号码的电子邮件,然后您可以相应地附加验证。