Reputation: 1595
I am trying to allow alphanumeric and some special characters
var regx = /^[A-Za-z0-9._-\] ]+$/;
I tried escaping the ] sign with the forward slash but it still doesnt work. What am I missing
Upvotes: 1
Views: 450
Reputation: 31035
If you try your regex on an online regex tester like regex101 you'd get the error:
You have to escape -
using \-
:
^[A-Za-z0-9._\-\] ]+$
Btw, you can shorten your regex to:
^[\w.\-% ]+$
Edit: added regex for your comment:
^[\w.-\]\[ #$>()@{}'"]+$
Upvotes: 1
Reputation: 272436
You also need to escape the -
character:
/^[A-Za-z0-9._\-\] ]+$/
//------------^
Escaping -
is not always necessary. Here, however, it is used inside square brackets which makes the JavaScript engine assume that you are trying to specify the range from _-]
which causes a "Range out of order in character class" error.
Note that /[_-a]/
is valid regex and matches characters _
, `
and a
(ASCII codes 95...97); which may not be the desired outcome.
Upvotes: 4