开发者

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 opti开发者_如何学运维on)...Please help


Test a string for consecutive digits:

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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜