gpt4 book ai didi

reactjs - 满足最少条件时如何使用 yup 验证密码

转载 作者:行者123 更新时间:2023-12-05 00:44:49 27 4
gpt4 key购买 nike

我正在尝试使用 yup 进行密码验证,其中至少满足 4 个密码条件中的 3 个。我很难找到现有的方法来做到这一点。

我的要求是这样的:

At least 8 characters It must use characters from at least three ofthe following four character types: • English alphabet uppercaseletters (A-Z) • English alphabet lowercase letters (a-z) • Numerals(0-9) • Non-alphanumeric symbols (such as !, #, $, %)

我的 yup 验证(使用 react-hook-form)是这样的:

newPassword: yup
.string()
.required('Please enter a password')
.min(8, 'Password too short')
.matches(/^(?=.*[a-z])/, 'Must contain at least one lowercase character')
.matches(/^(?=.*[A-Z])/, 'Must contain at least one uppercase character')
.matches(/^(?=.*[0-9])/, 'Must contain at least one number')
.matches(/^(?=.*[!@#%&])/, 'Must contain at least one special character'),

问题当然是这使得所有 4 个条件都需要,而 4 个条件中至少需要 3 个。任何有关解决此问题的帮助将不胜感激!谢谢

最佳答案

我建议您使用 yup 方法 yup.test() 在您有自定义测试时编写如下自定义测试函数,并且您也可以使用 yup 对其进行扩展。 addMethod() 如果要复用测试函数

 password: Yup.string()
.required("Please enter a password")
.min(8, "Password too short")
.test("isValidPass", " is not valid", (value, context) => {
const hasUpperCase = /[A-Z]/.test(value);
const hasLowerCase = /[a-z]/.test(value);
const hasNumber = /[0-9]/.test(value);
const hasSymbole = /[!@#%&]/.test(value);
let validConditions = 0;
const numberOfMustBeValidConditions = 3;
const conditions = [hasLowerCase, hasUpperCase, hasNumber, hasSymbole];
conditions.forEach((condition) =>
condition ? validConditions++ : null
);
if (validConditions >= numberOfMustBeValidConditions) {
return true;
}
return false;
})

这是一个演示 codesandbox有一个工作示例

关于reactjs - 满足最少条件时如何使用 yup 验证密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65657804/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com