Mahavir Munot
Mahavir Munot

Reputation: 1464

JavaScript regex for at least 2 non alphabetic characters in any order

I am looking for JavaScript regex pattern to restrict at least 2 non alphabetic characters in any order. So far I have tried this.

/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]|[0-9])){2}/i.test('d1cdddd'); // Outputs true, should return false
/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]|[0-9])){2}/i.test('@'); // Outputs true, should return false
/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]|[0-9])){2}/i.test('aa@'); // Outputs true, should return false
/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]|[0-9])){2}/i.test('@aaaa'); // Outputs true, should return false
/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]|[0-9])){2}/i.test('xrg@aaaa'); // Outputs true, should return false
/(?=(.*[`!@#$%\^&*\-_=\+'/\.,]|[0-9])){2}/i.test('xrg4aaaa'); // Outputs true, should return false

The string can contain alphabets and (at least 2 numbers) or (at least 2 special characters) or (at least 1 number and at least 1 special character) in any order

Example of valid cases/strings:

  1. 1sfdfsd2

  2. asd12

  3. 3asd@df

  4. 22

  5. @^

  6. 2*

  7. *sff)f

  8. .(()2fd

Upvotes: 3

Views: 442

Answers (2)

The fourth bird
The fourth bird

Reputation: 163277

You could use character classes and ranges to specify which characters you want to allow to match.

If you don't want to allow whitespaces or other not specified characters you could use:

Note that the range #-/ matches from ASCII char 35 - 47 and :-> matches from ASCII char 58 - 62.

^[!#-/:->@^_|a-zA-Z\d]*[!#-/:->@^_|\d][!#-/:->@^_|a-zA-Z\d]*[!#-/:->@^_|\d][!#-/:->@^_|a-zA-Z\d]*$
  • ^ Start of string
  • [!#-/:->@^_|a-zA-Z\d]* Match 0+ times the allowed chars
  • [!#-/:->@^_|\d] Match a special char or digit
  • [!#-/:->@^_|a-zA-Z\d]* Match 0+ times the allowed chars
  • [!#-/:->@^_|\d] Match a special char or digit
  • [!#-/:->@^_|a-zA-Z\d]* Match 0+ times the allowed chars
  • $ End of string

Regex demo

Upvotes: 1

Tiego A. Nascimento
Tiego A. Nascimento

Reputation: 219

Try this simple Regex:

^.*[\d$&+,:;=?@#|'<>.^*()%!-].*[\d$&+,:;=?@#|'<>.^*()%!-].*$

You can add or remove any special characters you want inside the brackets

Test it: https://regex101.com/r/rkjPbb/1

Upvotes: 0

Related Questions