Question

I have a problem that a filed need to accept all the characters and digits (English, Arabic etc) except the special characters like

~!@#$%&*.()[]{}<>^+=:,;?/\'

more specifically only special characters will be treated as faulty.

I have wirite below code,

 var textToMatch='$a$';
 var pattern = /[^~!@#$%&*\[\]\{\}\<\>\^+=:,;?/\\]+$/
 var validationResult = pattern.test(textToMatch);

In this code it works well when I put "$$@" or "a$" in the textToMatch variable (result: (false)invalid as expected). N.B: it only works when the last character is any special character

but failed when I put any of the character (not special one) as last character in the textToMatch variable (result: (true) valid which is not expected) say for example: "$a".

I am really stucked here. any help will be highly appreciated.

Was it helpful?

Solution

The problem is that you only check the end of the string. You just need to add ^ at the beginning of your pattern, so the entire string needs to be composed of non-special characters

^[^~!@#$%&*\[\]\{\}\<\>\^+=:,;?/\\]+$
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top