是的,使用正则表达式和不区分大小写的验证
Yup validation with regex and case insensitive
我有一个密码重置表单,其中对新密码的验证应与正则表达式匹配,而不应与用户的用户 ID 匹配。 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
)
我有一个密码重置表单,其中对新密码的验证应与正则表达式匹配,而不应与用户的用户 ID 匹配。 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
)