Validate repeated numbers using JavaScript in AngularJS

Last Reply one month ago By dharmendr

Posted one month ago

Hi,

The number should not be next number and also don't allow repeated number

Validate consecutive numbers simultaneously using Regular Expression in AngularJS

ex:

1234 - invalid

1256 - invalid

1231 - invalid

could you please help me

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago Modified on one month ago

Hi mahesh213,

Check this example. Now please take its reference and correct your code.

HTML

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $window) {
            $scope.Save = function () {
                var number = $scope.Number;
                var numberArray = [];
                if (number.length == 4) {
                    var array = ("" + number).split("");
                    var prevNumber;
                    for (var i = 0; i < array.length; i++) {
                        if (i == 0) {
                            numberArray.push(array[i]);
                            prevNumber = array[i];
                        } else {
                            var current = array[i];
                            if (prevNumber == (parseInt(current) - 1) || prevNumber == current
                                || numberArray.indexOf(array[i]) !== -1) {
                                $window.alert('Invalid');
                                break;
                            }
                            numberArray.push(array[i]);
                            prevNumber = array[i];
                        }
                    }
                } else {
                    $window.alert('Numbers should be 4 digit.');
                }
            }
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <input type="text" maxlength="4" ng-model="Number" />
    <input type="button" ng-click="Save()" value="Save" />
</body>
</html>

Demo