[英]Regex for form field validation
我有一个表单,它有一个特殊类型的字段。这需要验证。 状况
我试过这个模式
/[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]); } }
注意:如果您打算使用它作为密码,这样的规则是一个坏主意,现在正式不鼓励
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.