我有一个具有特殊类型字段的表单。这需要验证。条件
我试过这种模式
/[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 code generator的例子:
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]);
}
}
注意:如果您打算使用此密码,rules like this are a bad idea现在正式劝阻