javascript - 用于表单字段验证的正则表达式
问题描述
我有一个具有特殊类型字段的表单。这需要验证。条件
- 它必须包含至少 1 个字母。允许大写和小写 [强制]
- 它可以包含一个数字[可选]
- 它可以包含以下特殊字符中的任意 1 个或全部 3 个:连字符 (-)、和号 (&)、句点 (.)[可选]
- 长度 最小 5 最大 100
- 可以在字母之间包含空格 [可选]
我试过这个模式
/[a-zA-Z0-9]+|[\s]+|[\.]+|[\&]+|[\-]+/
但它没有给出预期的输出。
例子:
abcd xyz ->must pass test(letter must, 5<characters count<100,space optional)
abcdxyz ->must pass test(letter must, 5<characters count<100,space optional)
abcd & ->must pass test
abcd1234 ->must pass test
abcd.xyz.12 ->must pass test
123456 ->must fail test(no letters found)
&&&&&&& ->must fail test(no letters found)
&&&--..& ->must fail test(no letters found)
123 abcd.xyz 777-& !$ ->must fail test(!$ are not allowed)
我可以单独计算字符串长度,但其余部分需要正则表达式。我在用
str.match(/regex/)
解决方案
如果您可以单独测试长度,这可以完成这项工作:^(?:[a-zA-Z0-9 .&-]*)?[a-zA-Z]+(?:[a-zA-Z0-9 .&-]*)?$
. 在这里很难计算的是,它{5,100}
会测试子模式的出现次数,而不是它找到的字母总数。
解释(按顺序):
- 字符串的开头
- 可以选择查找任意数量的字母/数字和“.&-”
- 必须找到至少一个字母
- 可以选择查找任意数量的字母/数字和“.&-”
- 字符串结尾
改编自Regex101 代码生成器的示例:
const regex = /^(?:[a-zA-Z0-9 .&-]*)?[a-zA-Z]+(?:[a-zA-Z0-9 .&-]*)?$/;
const strs = [
'abcd xyz',
'abcdxyz',
'abcd &',
'abcd1234',
'abcd.xyz.12',
'123456',
'&&&&&&&',
'&&&--..&',
'123 abcd.xyz 777-& !$'
];
let m, i, l = strs.length;
for(i = 0; i < l; i++){
if( (m = strs[i].match(regex)) ){
console.log('Found match: ', m);
}else{
console.log('Doesn\'t match: ', strs[i]);
}
}
注意:如果你打算用它作为密码,像这样的规则是个坏主意,现在正式不鼓励
推荐阅读
- travis-ci - travis 上的 Codesign 挂起构建
- sql - Sql根据其他两个ID的两列获取MAX和MIN值
- python - 高效地查找多个维度上的邻居并根据邻近度计算值的总和
- visual-studio - 在 Visual Studio 中,您在哪里可以看到“调试”和“发布”的实际作用?
- python - 在 pyspark 数据帧中读取 tar.gz 文件中的特定 csv 文件
- crm - 如何在 Unified Service Desk 中捕获点击拨号事件?
- sql - 在同一代码块的更新中重用计算列
- javascript - 将变量传递给 JQuery 函数
- java - 从路径中捕获元素
- loopbackjs - Loopback 4 REST 控制器路径返回 NotFoundError 404