首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Yup验证:排除方法'.matches()‘中的某个模式

Yup验证:排除方法'.matches()‘中的某个模式
EN

Stack Overflow用户
提问于 2019-12-10 13:35:35
回答 2查看 9.4K关注 0票数 7

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

在下面的示例中,regex本身是工作的。但是,结合.matches()方法,它不验证字段。

代码语言:javascript
复制
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
  });
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-11 09:17:47

结果表明,只有当您提供的Regex返回为正时,匹配才会验证无效的错误。

如果您想验证一个否定的“匹配”(a.k.a )。不是操作符regex匹配),您可以使用.test()方法。

在文档中,它不是在字符串中提到的,而是在混合 (来源)中提到的。

代码语言:javascript
复制
mixed.test(name: string, message: string | function, test: function): Schema

因此,在我的例子中,我最终得到了:

代码语言:javascript
复制
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)
      ),

希望这能帮上忙。

票数 16
EN

Stack Overflow用户

发布于 2022-07-04 18:26:45

添加到这里的“否定正则匹配”讨论中,以显示另一个示例。

是的,如果正则表达式使用负查找功能生成regex,则可以使用Yup.matches()。例如,如果我不想从一个无线电组中选择一个选项,其中包含“偏好”一词:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59268460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档