asl*_*tor 6 javascript validation node.js yup
我有 3 个字段phone1、phone2 和phone3。我想进行验证,因此如果全部为空,它应该发出警报。意味着如果这 3 个字段中的任何一个具有值,则验证应该通过并且不会发出警报。
我为此使用了Yup 库。现在我已经创建了下面的代码,它实际上需要所有 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"),
});
Run Code Online (Sandbox Code Playgroud)
我相信我必须使用 Yup JS 的 .test() 方法,它允许自定义验证,但我不确定在这种情况下如何编写它。我正在使用 Express 框架来读取请求。
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']])
Run Code Online (Sandbox Code Playgroud)
然后您可以通过以下方式检查此验证:
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']])
Run Code Online (Sandbox Code Playgroud)
输入三个字段中的任何一个都不会收到错误消息。
例如
schema.validate({ phone1: '', phone2: '', phone3: '' }).catch(function (err) {
console.log(err.errors[0]);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4073 次 |
| 最近记录: |