javascript - 是的,使用正则表达式进行验证并且不区分大小写

标签 javascript reactjs react-final-form yup

我有一个密码重置表单,其中新密码的验证应与正则表达式匹配,并且不应与用户的 userId 匹配。 userId 检查必须不区分大小写。

我尝试了小写方法,但正则表达式验证失败,因为在验证开始之前该值已转换为小写。

  newPassword: yup
        .string()
        .notOneOf(
          [yup.ref("oldPassword")],
          "New password must be different than current password."
        )
        .matches(REGEX_PASSWORD, "Password does not meet requirements.")
        .lowercase()
        .notOneOf(
          [userId.toLowerCase()],
          "New password must not be same as userId"
        )

是否有任何方法可用于转换仅用于 userId 检查的值,以便我可以执行不区分大小写的检查,而不必担心正则表达式失败。

最佳答案

使用 Yup 时,如果所有正常功能都失败,您可以使用 .test 功能,记录在此处 - https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema

mixed.test(name: string, message: string | function, test: function): Schema

Adds a test function to the validation chain. Tests are run after any object is cast. Many types have some tests built in, but you can create custom ones easily. In order to allow asynchronous custom validations all (or no) tests are run asynchronously. A consequence of this is that test execution order cannot be guaranteed.

正如您从引用的文本中注意到的那样,测试(包括 Yup 内置的测试,例如您通常使用的测试)发生在对象被转换之后,因此您的问题。但是,通过进行自己的测试,您可以将值转换到内部并执行您想要的任何逻辑。在您的实例中,它可能看起来像这样:

 newPassword: yup
    .string()
    .notOneOf(
      [yup.ref("oldPassword")],
      "New password must be different than current password."
    )
    .matches(REGEX_PASSWORD, "Password does not meet requirements.")
    .test(
      'uidCheck',
      'New password must not be the same as userId',
      (item) => item !== undefined ? item.toLowerCase() !== userId.toLowerCase() : true
     )

关于javascript - 是的,使用正则表达式进行验证并且不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57587741/

相关文章:

reactjs - 是否有任何函数可以在 react-final-form 中获取表单值

javascript - 数据表中的数据操作

javascript - 从另一个页面的输入中预填充表单数据

javascript - 如何将变量数据放入 div Jquerymobile

javascript - react Js 警告 : Each child in a list should have a unique "key" prop

javascript - 为什么模糊事件不会在文本区域上 react ?

javascript - jqgrid选择: having different option text in form than on table

reactjs - 如何删除 React Router 中的最后历史记录?

javascript - 如何将个人资料图片设置为名字和姓氏的首字母?

javascript - 出现错误 : Warning: Failed prop type: Invalid prop `children` supplied to `Form` , 需要 ReactNode