Trying to build regex for string (company/organisation name) with below conditions:
- no leading or trailing space
- no double space in between
- shouldn't allow only single character (alphanumeric or white listed)
- can start with alphanumeric or white listed character
- shouldn't allow any white listed character entered multiple times
regex for these: /(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_')); // shouldn't allow
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('a')); // shouldn't allow
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc')); // shouldn't allow
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_123')); // works fine
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('# abc')); // works fine
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc!')); // works fine
console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc# abc')); // works fine
current regex doesn't match all the criteria and couldn't figure out what's the problem with regex ?
/^[a-zA-Z0-9_.#&-]+(?:\s[a-zA-Z0-9_.#&-]+)*$/
– Wiktor Stribiżew/^[a-zA-Z0-9_.#&-]+(?: [a-zA-Z0-9_.#&-]+)*$/.test('#')
this should return false but it returns true. – Valay!
, but your regex does not have it. I added!
to the character class in my answer. You may add more chars there, but mind-
must stay at the end of the character class, right before]
. – Wiktor Stribiżew