-1

I want to validate user's input and i use the following (which works fine) as regex.

 pattern = /^[a-zA-Z0-9 .,!?;-]+$/;

But when i try with all the characters i want, which is this.

pattern = /^[a-zA-Z0-9 .,!?;-:()@'+=/]+$/;

It doesn't work and I dont know why. Also, I would appreciate it a lot if you explained to me what's the difference when I add the ^ and the +$. Also i have tried using \s instead of space, and it still doesn't work(I prefer just space because i want to restrict line change).

NiXt
  • 61
  • 6

1 Answers1

0

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 .,!?;-:()@'+=/]+$/;
Makyen
  • 31,849
  • 12
  • 86
  • 121