使用 Yup 和 Formik 创建带有个别错误消息的强密码
Creating a strong password with Yup and Formik with individual error messages
我有什么
我正在尝试创建一个验证输入强度的密码字段,在另一个 中,我发现 regex
我可以用来验证输入是否满足特定条件,这种方法的问题是它对每个验证只抛出一条错误消息。
password: yup
.string()
.required('Please Enter your password')
.matches(
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
"Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
),
我想要什么
我想要的是验证用户输入的每个字符并在满足每个条件时抛出特定错误,例如,如果用户输入缺少小写字母,它应该抛出错误 'must have a lower case',如果输入缺少一个数字,它应该抛出数字 'must have a number' 等等。我试过的是使用匹配,但这不起作用:
password: yup
.string()
.required('Please Enter your password')
.matches(/^[a-z]+$/, 'One lowercase character')
.matches(/^[A-Z]+$/, 'One uppercase character')
.matches(/^\d+$/, 'One number')
// ... other validation
您只需从代码中删除 ^
(匹配输入的开头)和 $
(匹配输入的结尾)assertions,如下所示:
password: Yup.string()
.required("Required")
.min(8, "Must be 8 characters or more")
.matches(/[a-z]+/, "One lowercase character")
.matches(/[A-Z]+/, "One uppercase character")
.matches(/[@$!%*#?&]+/, "One special character")
.matches(/\d+/, "One number"),
这里是demo.
我有什么
我正在尝试创建一个验证输入强度的密码字段,在另一个 regex
我可以用来验证输入是否满足特定条件,这种方法的问题是它对每个验证只抛出一条错误消息。
password: yup
.string()
.required('Please Enter your password')
.matches(
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
"Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
),
我想要什么
我想要的是验证用户输入的每个字符并在满足每个条件时抛出特定错误,例如,如果用户输入缺少小写字母,它应该抛出错误 'must have a lower case',如果输入缺少一个数字,它应该抛出数字 'must have a number' 等等。我试过的是使用匹配,但这不起作用:
password: yup
.string()
.required('Please Enter your password')
.matches(/^[a-z]+$/, 'One lowercase character')
.matches(/^[A-Z]+$/, 'One uppercase character')
.matches(/^\d+$/, 'One number')
// ... other validation
您只需从代码中删除 ^
(匹配输入的开头)和 $
(匹配输入的结尾)assertions,如下所示:
password: Yup.string()
.required("Required")
.min(8, "Must be 8 characters or more")
.matches(/[a-z]+/, "One lowercase character")
.matches(/[A-Z]+/, "One uppercase character")
.matches(/[@$!%*#?&]+/, "One special character")
.matches(/\d+/, "One number"),
这里是demo.