Bee*_*ice 9 javascript validation typescript yup
我对是的很陌生。我试图验证字段可以是遵循某个正则表达式的字符串,也可以是此类字符串的数组。
这是检查字符串与我的正则表达式匹配的工作示例
{ field: yup.string().matches(regex) }
Run Code Online (Sandbox Code Playgroud)
现在我想field如果它有一个这样的字符串数组也是有效的:
{field: yup.array().of(yup.string().matches(regex))}
Run Code Online (Sandbox Code Playgroud)
但我如何将两者结合起来呢?我试过了:
{
field: yup.mixed().when('field', {
is: Array.isArray,
then: yup.array().of(yup.string().matches(regex)),
otherwise: yup.string().matches(regex)
})
}
Run Code Online (Sandbox Code Playgroud)
但我可以理解地得到了循环依赖错误,因为该字段依赖于自身。正确的语法是什么?
yup.mixed().test('test-name', 'error-msg', (value) => {
if (Array.isArray(value))
for (let i = 0; i < value.length; i++) {
if (!new RegExp('your-regx').test(value[i])) {
return false;
}
}
else {
if (!new RegExp('your-regx').test(value)) {
return false;
}
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5258 次 |
| 最近记录: |