reactjs - 是的验证,一个字符串上有 2 个正则表达式
问题描述
我有这个架构可以根据几个要求验证 2 个密码字段:
- “密码必须包含 8 个或更多字符,至少一个大写字母和一个数字。”
- “密码不能包含除 _ @ 以外的特殊字符。-”
现在我在一个字符串中显示两个验证错误,但我需要为这些条件显示 2 个单独的错误。
问题是,我如何创建 2 个在验证时不会相互冲突的正则表达式,并向我显示必要的错误?
const format = /[a-z`!#$%^&*()+=\[\]{};':"\\|,<>\/?~]/;
const passwordFormat = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d_@.-]{8,}$/;
return yup.object().shape({
password: yup
.string()
.required("Password is required")
// validates the password
.matches(passwordFormat, "Password must have 8 or more characters, at least one uppercase letter, and one number.")
//checks if there are special characters
.test('special-chars', "Password cannot contain special characters other than _ @ . -", function(value) {
return format.test(value);
})
.strict(true)
});
解决方案
你可以试试这两个:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\S]{8,}$ - "Password must have 8 or more characters, at least one uppercase letter, and one number"
^[-@\.\w]*$ - "Password cannot contain special characters other than _ @ . -"
推荐阅读
- azure-devops - 限制团队访问区域和/或工作项
- azure - Terraform:如何最好地遍历一组目录并为每次迭代应用带有 azure 广告查找的 gen2 ace 块
- c# - 使用 HttpClient 的 NLog 重复属性
- excel - VBA + 宏 + 对于每个单元格条件错误
- javascript - 无法读取未定义的属性 0 - 即使使用条件渲染
- ios - 上传并保存文档后创建文件夹
- delphi - 使用 FMX 绘图功能的 Windows 预览处理程序?
- java - 如何在Android中更改私人文件根目录
- java - 如何解决 spring boot 和 Thymeleaf 上的这个错误?
- java - 得到这个异常:给定最终块没有正确填充。如果在解密期间使用了错误的密钥,则可能会出现此类问题