1

I am trying to allow alphanumeric and some special characters

var regx = /^[A-Za-z0-9._-\] ]+$/;

I tried escaping the ] sign with the forward slash but it still doesnt work. What am I missing

2
  • what are you testing, and what went wrong? Commented Aug 28, 2014 at 20:01
  • I believe you mean the backslash(\), not the forward slash (/). Commented Aug 28, 2014 at 20:03

2 Answers 2

4

You also need to escape the - character:

/^[A-Za-z0-9._\-\] ]+$/
//------------^

Escaping - is not always necessary. Here, however, it is used inside square brackets which makes the JavaScript engine assume that you are trying to specify the range from _-] which causes a "Range out of order in character class" error.

Note that /[_-a]/ is valid regex and matches characters _, ` and a (ASCII codes 95...97); which may not be the desired outcome.

Sign up to request clarification or add additional context in comments.

Comments

1

If you try your regex on an online regex tester like regex101 you'd get the error:

Regex link

enter image description here

You have to escape - using \-:

^[A-Za-z0-9._\-\] ]+$

Btw, you can shorten your regex to:

^[\w.\-% ]+$

Edit: added regex for your comment:

^[\w.-\]\[ #$>()@{}'"]+$

Working demo

2 Comments

I modified the regex : var regx = /^[A-Za-z0-9._-% ]+$/; I included % and now when I run it in Chrome I get syntax error range out of order in character class. I would like to include special characters like #$>[]()@{}'" and alphanumeric.
@Mary I've updated my answer for your comment. Regex has special characters that need to be escaped, so dash is one that you need to escape it as \-. Btw, if your question is answered you may consider marking your question as solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.