Regular expression to check all digits the same or not

I have an input field that takes 12 digits. I want to throw an error when the user enters 12 digits of the same number. At least one number must be different.

For instance,

   111111111111 - Error

   111111111112 - Ok

   123456789012 - Ok

I tried this (but I want to invert the given regular expression)

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

code from: stack overflow

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

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

+4
source share
1 answer

You can use this regex:

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

RegEx Demo


Explanation:

  • ^ - start of the match line
  • (\d) - # 1, .. \1
  • (?!..) -
  • (?!\1+$) , ( ) .
  • \d{11}$ 11- ,
+8

All Articles