对动态数据类型(电子邮件或电话号码)的登录ID进行验证。

问题描述 投票:0回答:1

我正试图使用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."),});

但我的loginId可以是电话号码或电子邮件。那么,我如何根据表单中输入的字段类型添加验证。如果是电子邮件,触发电子邮件的验证,或者如果是电话号码,我想根据一个regex验证它。

reactjs forms react-hooks formik yup
1个回答
1
投票

如果你想动态地验证你的字段,可以使用 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)),
});

因此,在你的情况下,你必须制作你的 is 语句来决定是否是一个电话号码的邮件,然后你就可以附加相应的验证。

© www.soinside.com 2019 - 2024. All rights reserved.