使用Yup进行条件表单验证

时间:2019-12-12 16:25:34

标签: reactjs validation formik yup

我是Yup的初学者,我需要对Yup进行一些表单验证。这是我的架构的示例:

test

我的表格在两种情况下有效:用户输入contactID或输入phoneNumber和电子邮件。

我尝试使用public static void main(String[] args) { int row = (int)(Math.random() * 5 + 1); int column =(int)(Math.random() * 5 + 1); String[][] table = new String [row][column]; Scanner read = new Scanner(System.in); //String word = ""; for(int i = 0; i < table.length; i++) { for(int j = 0; j < table[i].length; j++) { System.out.print("Write a name of a fruit: "); String word = read.next(); 函数来实现此功能,但是无法做到这一点。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以为其余2个字段构建相同的逻辑:

Yup.object().shape({
    contactId: Yup.string().when(["phoneNumber", "email"], {
      is: (phoneNumber, email) => !phoneNumber || !email,
      then: Yup.string().required()
    }),
    phoneNumber: Yup.string().when("contractId", {
      is: contactId => !!contactId,
      then: Yup.string().required()
    }),
    email: Yup.string().when("contractId", {
      is: contactId => !!contactId,
      then: Yup.string()
        .email()
        .required()
    })
});

要检查电子邮件,可以使用内置功能 Yup.email()。对于电话,您需要构建自定义验证器:

const PHONE_VALIDATOR = /...your RegEx here.../

...
phoneNumber : Yup.string().matches(PHONE_VALIDATOR, 'Phone is not valid').required()
相关问题