chad
chad

Reputation: 564

RegEx won't limit max characters

I am attempting to limit the length to 20 characters. The lower limit is honored but the upper limit is not.

^\+([\s]*[\d]+[\s]*){1,20}$

What do I need to do in order to prevent more than 20 characters?

Upvotes: 0

Views: 84

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30985

If your string can have spaces and digits, then you can use:

^\+[\d\s]{0,19}$

Upvotes: 1

anubhava
anubhava

Reputation: 784958

Limit {1,20} is being applied to whole group ([\s]*[\d]+[\s]*).

You can use a lookahead to assert min and max length:

^(?=.{1,20}$)\+\s*\d+\s*$

(?=.{1,20}$) is a positive lookahead that asserts length of input between 1 and 20.

Upvotes: 2

Related Questions