validationRegex to accept/validate listed characters

5 to 16 alpha or alphanumeric to include special characters such as:
◦*Hyphen ( – )
◦*Slash ( / )
◦*Backslash ( )
◦*Asterisk ( * )
◦*Dollar Sign ( $ )
◦*Period ( . )
◦*Ampersand ( & )
◦*Comma ( , )
◦*Number Sign ( # )
◦*Open Parenthesis ( ( )
◦*Closed Parenthesis ( ) )
◦*Colon ( : )

Current code example:

PASSWORD: {id: password, label: PASSWORD, name: PASSWORD, validationRegex: ^[a-zA-Z0-9]+$, minLength: 5, maxLength: 16, errorMsg: message}

Go to Source
Author: Marcus

ANSWER

This regular expressions pattern should work to validate that the string is between 5 to 16 characters long, and has alphanumeric only with the special symbols allowed. Escaping those symbols so it is interpreted by regex compiler as a literal.

^([a-zA-Z0-9!-\?\\/.\,\$*\&\:()]{5,16})$

Results for the following samples of strings that pass the pattern and failed.

Passed

  • thequickbrownfox
  • !hello-world?
  • /hi\/there\
  • two
  • ast*risk*
  • $dollar$sign
  • 192.168.0.1
  • hello,world
  • (xx&:xx)
  • hashtag#allowed
  • 1234567890123456

Failed

Falls short of 5 characters or over 16 characters, does not have those special characters in the pattern, and with spaces or other whitespace characters.

  • abc1
  • this%not@allowed
  • iamoversixteencharacterslong
  • spaces not allowed
  • 12345678901234567