I am using javascript regex to do some data validation and specify the characters that i want to accept (I want to accept any alphanumeric characters, spaces and the followi
Your regex is not in line with what you said:
I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed
If you want to accept only those characters, you need to remove the caret:
var pattern = /^[A-Za-z0-9 "!&,'\\-]+$/;
Notes:
A-z
also includesthe characters:
[\]^_`.
Use A-Za-z
or use the i
modifier to match only alphabets:
var pattern = /^[a-z0-9 "!&,'\\-]+$/i;
\-
is only the character -
, because the backslash will act as special character for escaping. Use \\
to allow a backslash.
^
and $
are anchors, used to match the beginning and end of the string. This ensures that the whole string is matched against the regex.
+
is used after the character class to match more than one character.
If you mean that you want to match characters other than the ones you accept and are using this to prevent the user from entering 'forbidden' characters, then the first note above describes your issue. Use A-Za-z
instead of A-z
(the second note is also relevant).