Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – Regex for allowing only selected special characters only

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

I have tried the below :

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Eg :

var sampleText: string = "TestSample&123"

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading