作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想确保用户不会填写他们的用户名(模式是大写或小写的 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/
我是一名优秀的程序员,十分优秀!