2

I have the following regular expression in a validation rule:

^[a-zA-Z0-9',!;?~>+&\"\-@#%*.\s]{1,1000}$

However, I can enter ====== which I believe should not be allowed.

My thoughts is that somehow the - could cause trouble if not properly escaped or something but this is way over my head.

4
  • 1
    Eton, ask a question; what are you trying to do? Commented Oct 25, 2010 at 18:50
  • Do you want to escape the * and the . as well? I'm not a regex expert, but I know those are special characters. Commented Oct 25, 2010 at 18:50
  • In firebug, this returns false. Are you sure it's the regex and not some glue code you have elsewhere? /^[a-zA-Z0-9',!;?~>+&\"\-@#%*.\s]{1,1000}$/.test("======") Commented Oct 25, 2010 at 19:07
  • Yeah, now that I test this, I'm getting false as well. Can you show your actual code? Commented Oct 25, 2010 at 19:15

4 Answers 4

5

The regex you've shown us with the - escaped does not accept ===.
But if - is not escaped, === will be accepted. See this.

A - inside a regex is special and is used as range operator if it's not escaped and is surrounded by characters which participate as min and max in the range:

[a-z] matches any lowercase character.

[-az] matches either a - or a or z.

[az-] matches either a - or a or z.

[a\-z] matches either a - or a or z.

[a-c-d-f] matches a or b or c or - or d or e or f. The first and last - act as range operator but the one in the middle is treated literally.

In your case the = comes in the range "-@ and hence gets matched.

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

Comments

1
.

matches on everything. You want

\.

2 Comments

Sure? It's inside these brackets: []
I'm also pretty sure that this is the problem.
1

The - will be interpreted as a range indicator. You need to put it either first or last within the [] brackets if you want to match a literal -.

Comments

0

Your regex works fine for me but if I remove the escaping of - it matches =. I'm sure you are doing that.

Comments

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.