gee*_*rry 4 validation reactjs yup react-hook-form
我正在尝试使用 yup 进行密码验证,其中至少满足 4 个密码条件中的 3 个。我很难找到现有的方法来做到这一点。
\n我的要求是这样的:
\n\n\n至少 8 个字符 必须使用以下四种字符类型中至少三种\n的字符: \xe2\x80\xa2 英文字母大写\n字母 (AZ) \xe2\x80\xa2 英文字母小写字母 (az) \xe2\ x80\xa2 数字\n(0-9) \xe2\x80\xa2 非字母数字符号(例如 !、#、$、%)
\n
我的验证(使用react-hook-form)是这样的:
\nnewPassword: yup\n.string()\n.required('Please enter a password')\n.min(8, 'Password too short')\n.matches(/^(?=.*[a-z])/, 'Must contain at least one lowercase character')\n.matches(/^(?=.*[A-Z])/, 'Must contain at least one uppercase character')\n.matches(/^(?=.*[0-9])/, 'Must contain at least one number')\n.matches(/^(?=.*[!@#%&])/, 'Must contain at least one special character'),\nRun Code Online (Sandbox Code Playgroud)\n问题是,这当然需要所有 4 个条件,而实际上只需要 4 个条件中的至少 3 个。任何解决此问题的帮助将不胜感激!谢谢
\nCha*_*ine 10
我建议您使用 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;
})
Run Code Online (Sandbox Code Playgroud)
这是一个带有工作示例的演示codesandbox
| 归档时间: |
|
| 查看次数: |
4948 次 |
| 最近记录: |