gpt4 book ai didi

javascript - 是的模式验证 : Exclude a certain pattern in the method '.matches()'

转载 作者:行者123 更新时间:2023-11-30 19:03:15 29 4
gpt4 key购买 nike

我想确保用户不会填写他们的用户名(模式是大写或小写的 u,后跟 7-10 位数字:U0000000)

在下面的示例中,正则表达式本身确实有效。但是,与 .matches() 方法结合使用时,它不会验证该字段。

const schema = Yup.object()
.shape({
myField: Yup.string()
.matches(/.*\d/, 'Should contain a digit') // <- this works
.matches(/(?!.*[uU]\d{7,10})/, 'Should not contain a user ID') // <- this does not
});

最佳答案

事实证明,如果您提供的正则表达式返回正则匹配只会验证无效错误。

如果您想验证否定的“匹配”(又名不是运算符正则表达式匹配),您可以使用 .test() 方法。

在文档中,它没有在string 下提及,而是在mixed(source) :

mixed.test(name: string, message: string | function, test: function): Schema

所以在我的示例中,我得到了:

const containsDeviceId = (string) => /d\d{7,10}/.test(string);
const schema = Yup.object()
.shape({
myField: Yup.string()
.matches(/.*\d/, 'Should contain a digit')
.test(
'Should not contain a user ID',
'Should not contain a user ID',
(value) => !containsDeviceId(value)
),

希望这对某人有帮助。

关于javascript - 是的模式验证 : Exclude a certain pattern in the method '.matches()' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59268460/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com