angularJS ng-pattern not working

user3249448 picture user3249448 · Mar 24, 2014 · Viewed 16.2k times · Source

Please take a look plunker.

http://plnkr.co/edit/DuTFYbLVbPkCIvRznYjG?p=preview

where ng-pattern regEx is not going to apply on input text field.

where only required validation is applying properly.

HTML:

<body ng-controller="tableController">
    <form name="test">
        <div ng-repeat="model in models">
            <span ng-bind="model.caption"></span>
            <div ng-form name="frm{{$index}}">
                <input name="input{{$index}}"
                    ng-model="data[model.name]"
                    ng-disabled="model.isDisabled"
                    minlength="{{model.minlength}}"
                    maxlength="{{model.maxlength}}"
                    ng-show="model.isShow"
                    ng-pattern="model.pattern"
                    ng-required="true" />
                <br />
                {{data[model.name]}}
            </div>
        </div>
    </form>
    <br />
    <br />
</body>

JS:

angular.module("app", []).controller("tableController", function ($scope) {
        $scope.regEx = "/^\\d+$/";
        $scope.data = {};
        $scope.data.one = 234;
        $scope.data.two = 32432;
        $scope.models = [
            { name: "one", caption: "cOne", isDisabled: false, isShow: true, minlength: 2, maxlength: 10, pattern: "/^\d+$/" },
            { name: "two", caption: "cTwo", isDisabled: false, isShow: true, minlength: 2, maxlength: 5, pattern: "/^\d+$/" },
        ];
            });

Any suggestion ??

-Thanks

Answer

Sai picture Sai · Mar 24, 2014

Change the regular expression assignment to the below. Since it should be a regular expression. If you mention in double quotes then it becomes a string.

$scope.regEx = /^\d+$/;