Reputation: 3765
I am trying to validate that the given string contains contains only letters, numbers, spaces, and characters from a set of symbols (!-?():&,;+
). Here is what I have so far:
/^[a-zA-Z0-9 !-?\(\):&,;\+]+$/
Now this works somewhat but it accepts other characters as well. For example, strings containing *
or #
validate. I thought that the ^
at the beginning of the expression and the $
at the end meant that it would match the whole string. What am I doing wrong?
Thanks.
Upvotes: 2
Views: 96
Reputation: 145512
You have specified a "range" within your character class:
[!-?]
Means all ASCII symbols between !
and ?
http://www.regular-expressions.info/charclass.html
You need to escape the minus -
with a \
backslash. (OTOH the backslash is redundant before the +
and (
and )
within a character class.)
Upvotes: 2
Reputation: 26940
/^[a-zA-Z0-9 !-?\(\):&,;\+]+$/
The - is not nice where you placed it! If you want to place - inside a character class be sure to either place it first or last e.g.
/^[a-zA-Z0-9 !?\(\):&,;\+-]+$/
Otherwise it will take the range of ! until ? whatever this range maybe...Depends on your regex machine.
Finally special characters are not special inside character classes. So no need to escape most of them :
/^[a-zA-Z0-9 !?():&,;+-]+$/
Upvotes: 4