NiXt NiXt - 1 year ago 51
Javascript Question

Javascript regular expression character set limit

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
instead of space, and it still doesn't work(I prefer just space because i want to restrict line change).

Answer Source

The dash, -, has special meaning within a character set. It defines a range of characters. In you use, it needs to be escaped \- when used between ; and :.


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

Original with error:

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