【问题标题】:Validate if one out of 3 field is not empty using Yup JS使用 Yup JS 验证是否有三分之一的字段不为空
【发布时间】:2020-10-17 19:24:59
【问题描述】:

我有 3 个字段 phone1、phone2 和 phone3。 我想做一个验证,所以如果所有内容都是空的,它应该会发出警报。表示如果这 3 个字段中的任何一个具有值,则验证应该通过并且不警告。

我为此使用了Yup library。 现在我创建了下面的代码,它实际上需要所有 3 个字段。我不想要。

yup.object().shape({
    phone1: yup
        .string()
        .required("Please enter Phone 1"),
    phone2: yup
        .string()
        .required("Please enter Phone 2"),
    phone3: yup
        .string()
        .required("Please enter Phone 3"),
});

我相信我必须使用 Yup JS 的 .test() 方法,它允许自定义验证,但我不确定在这种情况下如何编写它。我正在使用 Express 框架来读取请求。

【问题讨论】:

    标签: node.js validation yup


    【解决方案1】:
    const schema = yup.object().shape({
      phone1: yup.string().when(['phone2', 'phone3'], {
        is: (phone2, phone3) => !phone2 && !phone3,
        then: yup.string().required('Please enter one of the three fields')
      }),
      phone2: yup.string().when(['phone1', 'phone3'], {
        is: (phone1, phone3) => !phone1 && !phone3,
        then: yup.string().required('Please enter one of the three fields')
      }),
      phone3: yup.string().when(['phone1', 'phone2'], {
        is: (phone1, phone2) => !phone1 && !phone2,
        then: yup.string().required('Please enter one of the three fields')
      })
    }, [['phone1', 'phone2'], ['phone1', 'phone3'], ['phone2','phone3']])
    

    那么你可以通过这种方式检查这个验证:

    schema.validate({ phone1: '', phone2: '', phone3: '' }).catch(function (err) {
      console.log(err.errors[0]);
    });
    

    输入三个字段中的任何一个以获取不出现错误消息。

    例如

    schema.validate({ phone1: '', phone2: '123', phone3: '' }).catch(function (err) {
      console.log(err.errors[0]);
    });
    

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2021-12-31
      • 2020-10-23
      • 2021-11-01
      • 2021-12-04
      • 1970-01-01
      • 2019-01-06
      • 2021-12-05
      • 1970-01-01
      相关资源
      最近更新 更多