我有一个表单,它有一个特殊类型的字段。这需要验证。使适应
我试过这个模式
/[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]);
}
}
注意:如果您打算使用它作为密码,这样的规则是一个坏主意,现在正式不鼓励
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句