waseem wani
waseem wani

Reputation: 1

Javascript Regular Expression to restrict user from Entering same consecutive digits in a text field

I want to restrict the user from entering same consecutive digits in a text field e.g User can't enter string like John22 or 22John or jo22hn....He can enter string like Joh2n2 , 2Joh2n and so on...All this has to be done in Javascript (Using regular expressions would be a better option)...Please help

Upvotes: 0

Views: 1116

Answers (3)

Sam Ruby
Sam Ruby

Reputation: 4340

Test a string for consecutive digits:

/(\d)\1/.test(string)

Upvotes: 3

Mutation Person
Mutation Person

Reputation: 30498

The following regex should help:

/[0-9]{2,}/

Or

/[\d]{2,}/

Although, you can match for all instances using the /g flag:

/[0-9]{2,}/g

See it at this JSFiddle

Upvotes: 0

stema
stema

Reputation: 92976

You can do this by using a negative lookahead.

^(?!.*(\d)\1).*$

See it here at Regexr

The ^ and the $ anchor the match at the start and the end of the string.

.* Will match everything (except newline characters)

The important part here is the Negative lookahead (?!.*(\d)\1) it will check the whole string for a digit \d put it in a capture group because of the brackets (\d) and reuse the value using the backreference \1 and the whole thing fails it there is a digit followed by the same digit.

Upvotes: 1

Related Questions