0

I'm trying to create regex for checking if password got special characters. https://www.owasp.org/index.php/Password_special_characters It looks like this

new RegExp('[!@#\$%\^\&*\)\(+=._\'",/<>?[\\\]`{|}~:;-\s]', 'g');

Unfortunately is also catching bare words: reg.test('word') it returns true. Whats wrong with my regex?

revo
  • 47,783
  • 14
  • 74
  • 117

2 Answers2

0

You can use negative/inverse logic and test against any character that is not a number or a letter.

Using [^A-Za-z0-9] where caret (^) matches everything except A-Za-z0-9.


const regex = /([^A-Za-z0-9]|[.\p{L}])/gm;

console.log('word: ' + regex.test('word'));
console.log('word!: ' + regex.test('word!'));
console.log('!£2word!: ' + regex.test('!£2word!'));
console.log('!ą,ć,ó!"£wordąćó: ' + regex.test('!ą,ć,ó!"£wordąćó'));
Alex
  • 2,164
  • 1
  • 9
  • 27
0

You didn't escape properly. RegExp object could receive a regular expression as a string but escaping matters: it needs double backslashes.

For now [;-\s] is equal to [;-s] which includes 57 characters:

[_;?\[\]@\\`\^<->aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsS-Z]

However, it should be [;\-\\s].

revo
  • 47,783
  • 14
  • 74
  • 117