0

I'm trying to create a directive to detect if numbers are Repetitive or not .
here is my fiddle : http://jsfiddle.net/7htqdk7y/3/
but it won't work , Any idea ?

Directive

app.directive('validTel', function () {
    return {
        require: '?ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$parsers.push(function (val) {
                var clean = val.replace(/[11111111111+22222222222+a-z+@]+/g, '');
                if (val !== clean) {
                    ngModelCtrl.$setViewValue(clean);
                    ngModelCtrl.$render();
                    console.log('hey');
                }
                return clean;
            });

            element.bind('keypress', function (event) {
                if (event.keyCode === 32) {
                    event.preventDefault();
                }
            });
        }
    };
});  

the rule is , user shouldn't enter Repetitive numbers like : 11111111111 or 22222222222
NOTE: I have another directive that controls count of numbers like : my-maxlentgh='11'

Sadeghbayan
  • 1,163
  • 2
  • 18
  • 38

2 Answers2

2

The regexp you want is this one:

(1){11,}|(2){11,}|(3){11,}|(4){11,}|(5){11,}|(6){11,}|(7){11,}|(8){11,}|(9){11,}|(0){11,}

It means:

digit 1: 11 or more times
  or
digit 2: 11 or more times
  etc...

whereas

(\d){11,}

would mean: there are eleven or more digits in your string

Manube
  • 5,110
  • 3
  • 35
  • 59
  • how should i use it in directive ? – Sadeghbayan Feb 10 '15 at 11:13
  • var clean = val.replace(/(1){11,}|(2){11,}|(3){11,}|(4){11,}|(5){11,}|(6){11,}|(7){11,}|(8){11,}|(9){11,}|(0){11,}/g, '') would erase a digit repeated 11 times or more, if this it what you mean to do – Manube Feb 10 '15 at 11:22
  • no i dont want to erase normal number like : 1234569878 or 02122411689 these are ok but 111111111111 these are not – Sadeghbayan Feb 10 '15 at 11:28
  • var clean = val.replace(/(1){11,}|(2){11,}|(3){11,}|(4){11,}|(5){11,}|(6){11,}|(7){11,}|(8){‌​11,}|(9){11,}|(0){11,}/g, '') would erase 11111111111,22222222222,33333333333 etc (up to 00000000000), but not other numbers like 12345678901 – Manube Feb 10 '15 at 11:30
1

Seems like you got the regex wrong. Try

var clean = var clean = val.replace(/[a-z+@]+/gi, '').replace(/(((\d){11,11})(\3)*)/g, '$2');

here is the modified fiddle: http://jsfiddle.net/7htqdk7y/4/

The second replace restricts digits to be repeated more then 11 times -- it strips all repetitions of a digit that are out of that scope.

I think that's a better solution than the accepted answer, because matches of repetitions aren't replaced completely, but only the part that we don't permit

See Regex to find repeating numbers

Community
  • 1
  • 1
Benjamin
  • 1,165
  • 7
  • 19