Reputation: 4424
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.
Upvotes: 0
Views: 953
Reputation: 172448
You can try to use the below regex:
const str = /^[a-zA-Z0-9?*=.@#$%!^":,:;<'>+-_]+$/;
console.log(str.test('TestSample&123'));
Upvotes: 0
Reputation: 13922
A few things:
var regex = /^(?=.*?[?*=.@#$%!^":,:;<'>+-_])/
instead of new Regex(...)
^(?=.*?[?*=.@#$%!^":,:;<'>+-_])
into that site and it'll explain what each part does.^
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.(?=.*?
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 = /^[?*=.@#$%!^":,:;<'>+-_]*$/
Upvotes: 1
Reputation: 13623
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
Upvotes: 1