0

I'm trying to do a search for a character in a string NOT matching the regex :

password.search(/[`!@@#$%^&*A-Za-z0-9]/i));. 

Basically, all characters that aren't this regex isn't allowed and I want to know if the user has input any characters that isn't allowed. For example, '\', or any other characters that I might not think of.

I'm pretty sure there's a question similar to this out somewhere, but despite trying to look for it I surprisingly couldn't find it. If this is a duplicate question please link me.

John Kim
  • 1,081
  • 10
  • 26

2 Answers2

0

f you want to exclude a set of characters (some punctuation characters, for example) you would use the ^ operator at the beginning of a character set, in a regex .

Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
0

According to this answer, you could use ?!:

console.log("valid$\\".search(/(?![`!@@#$%^&*A-Za-z0-9])/i));
console.log("256)128".search(/(?![`!@@#$%^&*A-Za-z0-9])/i));
shrys
  • 5,860
  • 2
  • 21
  • 36
  • I accepted your answer at first, but from further investigation it seems your code always returns index > 0 even if there is no illegal character. For example, "256128" returns 6 instead of -1. – John Kim Nov 19 '19 at 06:03
  • Never mind, instead of checking for < 0 I just did < password.length since if an illegal character didn't exist it always returned the size. – John Kim Nov 19 '19 at 06:22
  • thank you for pointing it out, I'll try to find a solution for that as well – shrys Nov 19 '19 at 06:31