IPr*_*ory 9 javascript validation yup formik
我有动态输入量的表单(管理员电子邮件),但是检查唯一性失败:
validationSchema={Yup.object().shape({
adminEmails: Yup.array()
.of(
Yup.string()
.notOneOf(Yup.ref('adminEmails'), 'E-mail is already used')
Run Code Online (Sandbox Code Playgroud)
这里最好的方法是什么?仅供参考,作为表单助手,我使用Formik.
ole*_*ank 15
尝试这个:
Yup.addMethod(Yup.array, 'unique', function(message, mapper = a => a) {
return this.test('unique', message, function(list) {
return list.length === new Set(list.map(mapper)).size;
});
});
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
const headersSchema = Yup.object().shape({
adminEmails: Yup.array().of(
Yup.string()
)
.unique('email must be unique')
})
Run Code Online (Sandbox Code Playgroud)
这是一个简单的内联解决方案,用于验证字符串数组仅包含唯一元素:
Yup.array().of(Yup.string())
.test(
'unique',
'Only unique values allowed.',
(value) => value ? value.length === new Set(value)?.size : true
)
Run Code Online (Sandbox Code Playgroud)
小智 5
如果你想在每个字段中出现错误而不是在数组中
Yup.addMethod(Yup.mixed, 'uniqueIn', function (array = [], message) {
return this.test('uniqueIn', message, function (value) {
return array.filter(item => item === value).length < 2;
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7526 次 |
| 最近记录: |