0

I want to allow only specific special characters like in a text like ?*=.@#$%!^":,:;<'>+-_.

I have tried the below code:

pattern = new RegExp(/^(?=.*?[?*=.@#$%!^":,:;<'>+-_])/);

It does not seem to work, it seems to pass even if I am entering a special character other than the ones specified above. Am I missing something here?

e.g.:

var sampleText: string = "TestSample&123"

The above example should throw an error and fail since I have not used any of the special character which is specified in the pattern.

double-beep
  • 5,031
  • 17
  • 33
  • 41
sTg
  • 4,313
  • 16
  • 68
  • 115

3 Answers3

1

Based on the charset you want and the approach from this answer here about exclusive sets in Regex, you should be able to do something like this:

const testPattern = /^[?*=.@#$%!^":,;<'>+\-_]+$/;

console.log(testPattern.test('?*+@!')); // passes
console.log(testPattern.test('TestSample&123')); // fails
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
1

A few things:

  • Javascript has regex literals, so you can do var regex = /^(?=.*?[?*=.@#$%!^":,:;<'>+-_])/ instead of new Regex(...)
  • https://regex101.com/ is a super helpful resource for figuring out regex. Paste ^(?=.*?[?*=.@#$%!^":,:;<'>+-_]) into that site and it'll explain what each part does.
  • The ^ at the beginning of the regex anchors the matching to the beginning of the string, but you don't have a corresponding $ to make sure the match applies to the entire string.
  • The (?=.*? is a positive lookahead that mathces any number of any character. The character group [...] that you have is only going to match a single character, when it sounds like you want it to match all of the characters.

Rahul already answered while I was typing this up, and he's got the right expression:

^[?*=.@#$%!^":,:;<'>+-_]*$

The ^ anchors the match to the beginning of the string, and the $ anchors the end of the match to the end of the string. The [...]* will match any number of characters as long as they belong to that set of characters.

You can make a JS var out this like

var myRegex = /^[?*=.@#$%!^":,:;<'>+-_]*$/
Dylan
  • 13,645
  • 3
  • 40
  • 67
0

You can try to use the below regex:

    const str = /^[a-zA-Z0-9?*=.@#$%!^":,:;<'>+-_]+$/;
    
    console.log(str.test('TestSample&123')); 
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • pattern = new RegExp(^[a-zA-Z0-9?*=.@#$%!^":,:;<'>+-_]+$); like this ???.. This gives me compile time error The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type – sTg Dec 09 '22 at 02:29