Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to check all digits in are same or not

I have input field which takes 12 digits number. I want to throw error when user enters 12 digits same number. Atleast one number has to be different.

E.g

   111111111111 - Error

   111111111112 - Ok

   123456789012 - Ok

I tried this (but i want inverse of the specified regex )

var pattern = "^([0-9])\\1{3}$";
var str = "5555";
pattern = new RegExp(pattern);
if(!pattern.test(str))
{
    alert('Error');
}
else
{
    alert('Valid');
}

code from : https://stackoverflow.com/a/2884414/1169180

Fiddle : http://jsfiddle.net/wn9scv3m/10/

Edit: No manipulation in if(!pattern.test(str)) in this line is allowed

like image 357
Shaggy Avatar asked Nov 21 '14 14:11

Shaggy


1 Answers

You can use this regex:

^(\d)(?!\1+$)\d{11}$

RegEx Demo


Explanation:

  • ^ - Match line start
  • (\d) - match first digit and capture it in back reference #1 i.e. \1
  • (?!..) is a negative lookahead
  • (?!\1+$) means disallow the match if first digit is followed by same digit (captured group) till end.
  • \d{11}$ match next 11 digit followed by line end
like image 109
anubhava Avatar answered Sep 19 '22 01:09

anubhava