The "hyphen-minus" character, -
, has special meaning within a character set (a set of characters between [
and ]
). It, -
, defines a range of characters. Most of the time in a character set that you want the -
to represent itself, you need to use \-
to escape its special meaning. In your use, -
needs to be escaped \-
when used between ;
and :
.
Working:
pattern = /^[a-zA-Z0-9 .,!?;\-:()@'+=/]+$/;
If you actually want the range of characters between :
and ;
, then you need to specify the one that has a lower character code (Ascii code chart, or Unicode) first. In this case, that means :-;
as :
comes before ;
:
Show :-;
range is valid:
pattern = /^[a-zA-Z0-9 .,!?:-;()@'+=/]+$/;
The same error would be generated if you were to try to specify a range such as z-a
.
Show same error with range of z-a
:
pattern = /^[z-aA-Z0-9 .,!?:-;()@'+=/]+$/;
The -
does not take on its special meaning if it is the first or last character in the character set.
Note: In some regular expression implementations, the -
does have its special meaning if you try to use it as the last character in the character set. You are better off just being in the habit of escaping it with \-
.
Using -
as first or last character in character set:
pattern = /^[-a-zA-Z0-9 .,!?;:()@'+=/]+$/;
pattern = /^[a-zA-Z0-9 .,!?;:()@'+=/-]+$/;
Original code with error:
pattern = /^[a-zA-Z0-9 .,!?;-:()@'+=/]+$/;