是的模式验证:在方法“.matches()”中排除某个模式

Rem*_*emi 2 javascript regex yup

我想,以确保用户不会在自己的用户名填写(图案是大写在前或小写字母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
  });
Run Code Online (Sandbox Code Playgroud)

Rem*_*emi 7

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

如果要验证否定的“匹配”(又名不是 operator regex match),可以使用该.test()方法。

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

mixed.test(name: string, message: string | function, test: function): Schema
Run Code Online (Sandbox Code Playgroud)

所以在我的例子中,我最终得到了:

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)
      ),
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人。

  • 我花了很长时间才找到解决我问题的答案。我已经在谷歌上搜索“反向正则表达式匹配”和“非运算符正则表达式匹配”几个小时了! (3认同)