【问题标题】:Yup schema validation: Exclude a certain pattern in the method '.matches()'是的模式验证:在方法“.matches()”中排除某个模式
【发布时间】:2020-04-03 17:05:54
【问题描述】:

我想确保用户不要填写他们的用户名(模式是大写或小写的 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
  });

【问题讨论】:

  • @WiktorStribiżew 这更像是一个 Yup 模式问题。正则表达式模式在架构之外也能正常工作。
  • /^(?!.*[uU]\d{7,10})//^(?!.*[uU]\d{7,10}).*/ 不起作用吗?
  • 是和不是。是的,这会过滤掉用户ID。否:它不能与 .matches() 方法一起使用。但一段时间后我找到了答案。如果您再次打开此问题,我可以添加它。
  • 我还编辑了问题以使其更清楚,因为它似乎不清楚。
  • 好的,请发布答案。

标签: javascript regex yup


【解决方案1】:

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

如果您想验证否定的“匹配”(又名不是运算符正则表达式匹配),您可以使用.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)
      ),

希望这对某人有所帮助。

【讨论】:

  • /(?=.*[dD]\d{7,10})/ 可以简化为/d\d{7,10}/i
  • 我花了很长时间才找到解决我问题的答案。我一直在谷歌搜索“反向正则表达式匹配”和“非运算符正则表达式匹配”几个小时!
猜你喜欢
  • 1970-01-01
  • 2021-10-30
  • 2019-07-03
  • 2019-04-27
  • 1970-01-01
  • 2022-10-19
  • 2017-09-02
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多