I have a form which has a field of a special type.this needs validation. Conditions
I tried this pattern
/[a-zA-Z0-9]+|[\s]+|[\.]+|[\&]+|[\-]+/
But it doesn't give the expected output.
examples:
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)
I can count the string length separately,but i need the regex for the rest part. I am using
str.match(/regex/)
If you can test length separately, this could do the job: ^(?:[a-zA-Z0-9 .&-]*)?[a-zA-Z]+(?:[a-zA-Z0-9 .&-]*)?$
. What makes it hard to count here is that {5,100}
would test the number of occurences of a subpattern and not the total of letters it found.
explanation (in order):
example adapted from 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]); } }
NOTE : If you meant to use this for a password, rules like this are a bad idea and now officially discouraged
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.