首页 > 解决方案 > 用于表单字段验证的正则表达式

问题描述

我有一个具有特殊类型字段的表单。这需要验证。条件

  1. 它必须包含至少 1 个字母。允许大写和小写 [强制]
  2. 它可以包含一个数字[可选]
  3. 它可以包含以下特殊字符中的任意 1 个或全部 3 个:连字符 (-)、和号 (&)、句点 (.)[可选]
  4. 长度 最小 5 最大 100
  5. 可以在字母之间包含空格 [可选]

我试过这个模式

/[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/)

标签: javascriptregex

解决方案


如果您可以单独测试长度,这可以完成这项工作:^(?:[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]);
    }
}

注意:如果你打算用它作为密码,像这样的规则是个坏主意,现在正式不鼓励


推荐阅读