JQuery RegEx. If the string contains any character except

I have this RegEx that is used to verify that the user enters

It must be a value of 8-16 characters long and may contain ONE of certain special characters.

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[:;#~]).{8,16}$"

I am not trying to show a warning if the user enters something that does not match the above. So az, AZ, 0-9 and are :;#~allowed, but everything else shows a warning.

So, Abcd1234#in order, but if they enter Abcd1234!$, if a warning is displayed like !they $do not match.

I tried adding ^ to the beginning of a character match to try to cancel them, but that didn't work.

What is the best way to do this?

+4
source share
1 answer

It seems you only need to specify the characters mentioned in lookaheads, create a character class with them and replace it with the last one .:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[:;#~])[\da-zA-Z:;#~]{8,16}$/
                                            ^^^^^^^^^^^^^^

Watch the regex demo

The template [\da-zA-Z:;#~]{8,16}will match 8-16 characters who are either numerals, ASCII-letters or symbols :, ;, #or ~.

More details

  • ^ - beginning of line
  • (?=.*\d)- there must be a digit after any 0+ characters other than line break characters (a (?=\D*\d)will be more effective because it is based on the principle of contrast )
  • (?=.*[a-z])- - there must be an ASCII letter in lower case after any 0+ characters other than line break characters (a (?=[^a-z]*[a-z])will be more efficient)
  • (?=.*[a-z]) - ASCII 0+, (a (?=[^a-z]*[a-z]) )
  • (?=.*[:;#~]) - :, ;, # ~ 0+, ( (?=[^:;#~]*[:;#~]))
  • [\da-zA-Z:;#~]{8,16} - 8 16 ,
  • $ - .
+2

Source: https://habr.com/ru/post/1681179/


All Articles