Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  141] [ 3]  / answers: 1 / hits: 59208  / 11 Years ago, fri, august 23, 2013, 12:00:00

I have the following regex which does not allow certain special characters:



if (testString.match(/[`~,.<>;':/[]|{}()-=_+]/)){    
alert(password not valid);
}
else
{
alert(password valid);
}


This is working. This regex will accept a password if it does not contain any of the special characters inside the bracket (~,.<>;':/[]|{}()-=_+).



My problem here is it also don't allow me to input numbers which is weird.



Anything I missed here? Thanks in advance!



Here is a sample:



jsFiddle


More From » regex

 Answers
5

You've got a character range in there: )-= which includes all ASCII characters between ) and = (including numbers). Move the - to the end of the class or escape it:



/[`~,.<>;':/[]|{}()=_+-]/


Also, you don't need to escape all of those characters:



/[`~,.<>;':/[]|{}()=_+-]/


Note that in your case, it is probably enough for you, to use test instead of match:



if (/[`~,.<>;':/[]|{}()=_+-]/.test(testString))){
...


test returns a boolean (which is all you need), while match returns an array with all capturing groups (which you are discarding anyway).



Note that, as Daren Thomas points out in a comment, you should rather decide which characters you want to allow. Because the current approach doesn't take care of all sorts of weird Unicode characters, while complaining about some fairly standard ones like _. To create a whitelist, you can simply invert both the character class and the condition:



if (!/[^a-zA-Z0-9]/.test(testString)) {
...


And include all the characters you do want to allow.


[#76187] Thursday, August 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;