ng-pattern regex throw error

时间:2017-02-06 05:10:16

标签: angularjs angularjs-directive ng-pattern

我正在使用ng-pattern来验证号码(逗号分隔输入字段仅允许号码)。但它在控制台中抛出以下错误,尽管它工作正常。谁能告诉我我做错了什么。

错误:SyntaxError:无效的正则表达式:/ ^ \ d + $ + \,/:无需重复     在新的RegExp()



barapp.directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;


            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });


            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
                return plainNumber;
            });
        }
    };
}]);

<input type="text" name="money" class="form-control text-center" placeholder="Money" ng-model="money" ng-pattern="/^\d+$+\,/" required format="number">
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你必须在模块中声明barapp。在行

之前尝试这个
var app = angular.module('barapp',[]);

barapp.directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;


            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });


            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
                return plainNumber;
            });
        }
    };
}]);