我想确保用户不填写他们的用户名(模式是一个调理大写或小写u,后面跟着7-10位数字:U0000000)
在下面的示例中,regex本身是工作的。但是,结合.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
});发布于 2019-12-11 09:17:47
结果表明,只有当您提供的Regex返回为正时,匹配才会验证无效的错误。
如果您想验证一个否定的“匹配”(a.k.a )。不是操作符regex匹配),您可以使用.test()方法。
在文档中,它不是在字符串中提到的,而是在混合 (来源)中提到的。
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)
),希望这能帮上忙。
发布于 2022-07-04 18:26:45
添加到这里的“否定正则匹配”讨论中,以显示另一个示例。
是的,如果正则表达式使用负查找功能生成regex,则可以使用Yup.matches()。例如,如果我不想从一个无线电组中选择一个选项,其中包含“偏好”一词:
const testYum = () => {
// Regex pattern matches if pattern is not in the value.
// The 'im' option at end of regex is to (i)gnore case and
// search over (m)ultiple lines in the value. Starts at beginning
// of line.
const notDeviceIdPattern = /^(?!.*[uU]\d{7,10}).*/im;
const yupToTest = Yup.object().shape({
password: Yup.string()
.required("This is needed")
.matches(/.*\d/, "Should contain a digit")
.matches(notDeviceIdPattern, "Do not embed device id")
});
// Change this to pattern to test.
const testPassword = { password: "sddsfasf" };
yupToTest
.validate(testPassword)
.then(function (value) {
alert("Valid password: " + JSON.stringify(value, null, 2));
})
.catch(function (err) {
alert("Invalid password: " + JSON.stringify(err.errors, null, 2));
});
};我希望这能帮上忙。关于这个主题的一个更好的讨论可以在这里找到:https://regexland.com/regex-match-all-except
https://stackoverflow.com/questions/59268460
复制相似问题