Reputation: 1464
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:
1sfdfsd2
asd12
3asd@df
22
@^
2*
*sff)f
.(()2fd
Upvotes: 3
Views: 442
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 stringUpvotes: 1
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